2011-05-08 76 views
1

我有一張表格,其中插入了數據標題和數據日期。 現在我想要做的是統計出它。在一條語句中計數倍數

我可以在一個SQL語句中進行多次計數嗎? 類似於,列日期,我想要統計本月有多少,以及今年有多少,直到選擇月份。可能嗎?如果是的話,怎麼樣?

這就是我現在想出來的。

SELECT a.trigger_type_code 
    , c.trigger_name 
    , COUNT(*) AS number 
FROM issue_trigger a 
    INNER JOIN cs_issue b 
    ON b.issue_id = a.issue_id 
    INNER JOIN ref_trigger_type c 
    ON c.trigger_type_code = a.trigger_type_code 
WHERE MONTH(b.created_date) = '05' 
    AND YEAR(b.created_date) = '2011' 
GROUP BY trigger_type_code,trigger_name 

通過這只是一個count.help :(

回答

0

我想你可能是這樣的:

SELECT 
    a.trigger_type_code, 
    c.trigger_name, 
    COUNT(MONTH(b.created_date) < 5 OR NULL) AS before_the_month, 
    COUNT(MONTH(b.created_date) = 5 OR NULL) AS in_the_month 
FROM issue_trigger a 
    INNER JOIN cs_issue b 
    ON b.issue_id = a.issue_id 
    INNER JOIN ref_trigger_type c 
    ON c.trigger_type_code = a.trigger_type_code 
WHERE YEAR(b.created_date) = 2011 
GROUP BY a.trigger_type_code, c.trigger_name 
1

你可以使用一個case

select sum(case when MONTH(b.created_date) = '05' 
      AND YEAR(b.created_date) = '2011' then 1 end) as Count_2011_05 
,  sum(case when YEAR(b.created_date) = '2011' 
      then 1 end) as Count_2011 
from ... etc ... 
+0

我個人會使用'SELECT MONTH(b.created_date),YEAR(b.created_date),COUNT(*)FROM ... GROUP BY MONTH(b.created_date),YEAR(b.created_dat E)' – 2011-05-08 09:18:03