Php,MySql,有两个计数的单个查询

时间:2015-11-07 21:25:42

标签: php mysql sql count

我需要在一个查询中执行两个不同的计数。

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;

如何将第二个查询纳入上述内容?

1 个答案:

答案 0 :(得分:3)

您可以使用COUNTCASE 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