我需要在一个查询中执行两个不同的计数。
First Query: count number of transactions from today 30 days back.
Second Query: count number of transactions from last 60 until last 30 days.
我的第一个查询工作正常:
SELECT
COUNT(*) AS sales
FROM
transactions
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND STATUS = 1;
如何将第二个查询纳入上述内容?
答案 0 :(得分:3)
您可以使用COUNT
和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;
或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