D
D
Dmitry Temnikov2021-02-21 16:50:32
SQL
Dmitry Temnikov, 2021-02-21 16:50:32

SQL. How to set a condition for the aggregating function COUNT?

There is a certain blog, two conditional entities - "publications" and "categories". Plus a link table. Task: pull out a list of categories, indicating the number of publications in the category as a whole and the number of publications in it in the last week.
I do so

SELECT category.cat_id, category.name, category.description, COUNT(catinpub.pub_id) as "count", 
MAX(publication.date) as "lastdate",
COUNT(publication.date BETWEEN '2021-03-27 00:00:00' AND '2021-04-01 23:59:59') as "qntlastweek" 
FROM category 
    LEFT JOIN catinpub ON catinpub.cat_id = category.cat_id
    LEFT JOIN publication ON publication.pub_id = catinpub.pub_id
    WHERE category.archive is NULL
    GROUP BY category.cat_id
    ORDER BY count DESC

Everything is fine, but the problem is in "it's the same for the last week"
6032644be8519485825049.pngPutting the publication.date BETWEEN '2021-03-27 00:00:00' AND '2021-04-01 23:59:59' clause in the WHERE block is incorrect, otherwise limited list of publications. In the query, you can put absolutely any value as a whole, for example, COUNT (1) or COUNT (0), but in the qntlastweek field it still displays the value of the first count.
How to set a condition for the aggregating function COUNT?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Temnikov, 2021-02-21
@exibit777

SELECT category.cat_id, category.name, category.description, COUNT(catinpub.pub_id) as "count", MAX(publication.date) as "lastdate",
COUNT(CASE WHEN publication.date BETWEEN '2021-03-27 00:00:00' AND '2021-04-01 23:59:59' THEN 1 ELSE NULL END) FROM category 
    LEFT JOIN catinpub ON catinpub.cat_id = category.cat_id
    LEFT JOIN publication ON publication.pub_id = catinpub.pub_id
    WHERE category.archive is NULL
    GROUP BY category.cat_id
    ORDER BY count DESC

Z
zoozag, 2017-10-25
@zoozag

This is very far from Opencart, so it's probably easier to write from scratch.
The mechanism is not very complicated.
1 select - Category
2 select - Products in this category
3 select - Several options like radio or select
Color - An option like image
The selects themselves on Select2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question