I need to perform two different counts in one single query.
First Query: count number of transactions from today 30 days back.
Second Query: count number of transactions from last 60 until last 30 days.
I have first query working fine as:
SELECT
COUNT(*) AS sales
FROM
transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1;
How can I incorporate the second query into the above?
You can use COUNT
and CASE WHEN
:
SELECT
COUNT(CASE WHEN DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) AS c1,
COUNT(CASE WHEN DATE(created) <= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) AS c2
FROM transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 60 DAY)
AND STATUS = 1;
or UNION
:
SELECT COUNT(*) AS sales
FROM transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1
UNION ALL
SELECT COUNT(*)
FROM transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 60 DAY)
AND DATE(created) < DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.