2011-06-06 86 views
1

我試圖編寫一個查詢,我可以每隔3個月在一個數據庫的事務表中獲得不同的user_id。將多個MySQL查詢合併爲一個

我可以手動實現的結果,如果我這樣做

SELECT COUNT(DISTINCT(user_id)) FROM transactions WHERE DATE(created_at) BETWEEN "2011-01-01" AND "2011-03-31". 

但是,如果我想在幾年的季度期間的自動運行這個它會永遠需要。

有沒有辦法在單個查詢中包裝這種東西?

回答

5
SELECT COUNT(DISTINCT user_id),YEAR(created_at), QUARTER(created_at) 
FROM transactions 
GROUP BY YEAR(created_at), QUARTER(created_at) 
+0

驚人。節省了很多時間。我沒有意識到GROUP BY有限制功能結果的效果。但很明顯,它會......呃!謝謝! – Darren 2011-06-06 23:05:59

3

這會做你在問什麼?

select user_id, year(created_at) as `year`, quarter(created_at) as `quarter`, count(*) 
from transactions 
group by user_id, year(created_at), quarter(created_at) 
1

什麼是這樣的:

SELECT COUNT(DISTINCT USER_ID), 
     QUARTER(created_at), 
     YEAR(created_at)  
    FROM transactions 
GROUP BY YEAR(created_at), QUARTER(created_at);