2015-11-07 61 views
1

我需要在一個查詢中執行兩個不同的計數。Php,MySql,兩個計數的單個查詢

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; 

我如何可以將第二查詢到上面?

回答

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 
+0

謝謝你的作品完美。我沒有測試聯盟,但使用案例更清潔。 – Alko

+0

@Alko不客氣。你可以[接受我的回答](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)如果你的問題已經解決了:) – lad2025