2011-04-04 37 views
4

使用表I和字段date_entered和代碼,我編寫了一個查詢來列出代碼='12A'的每一年的計數。T-SQL-在單個查詢中包含計數(*)的總和

select distinct year(date_entered) as Yr, count(*) as Cnt 
from i 
where code = '12A' 
group by year(date_entered) 
order by Yr desc 

這將產生:

Yr | Cnt 
2011 | 780 
2010 | 3489 
2009 | 3256 
... 

我想包括在我的結果集的CNT變量的總和。我知道如何使用單獨的查詢來查找總和,但我想在我的原始查詢中計算總和。

+2

注意:查詢中的「distinct」是超級的,因爲您在一年中進行分組,所有記錄都是唯一的。 – Guffa 2011-04-04 15:22:49

+0

@Guffa - 「distinct」和「group by」似乎是TSQL中最容易被誤解的概念。我見過20個不同列的人只是爲了獲得「正確」的數據。 :( – JonH 2011-04-04 15:24:31

回答

12

添加WITH ROLLUP到查詢GROUP BY條款後,你會得到一個額外的一行包含空YR您最終總數。

select year(date_entered) as Yr, count(*) as Cnt 
from i 
where code = '12A' 
group by year(date_entered) 
with rollup 
order by Yr desc 
+0

+1 Joe我喜歡彙總! – JonH 2011-04-04 15:20:14

+0

優秀的解決方案。謝謝!!! – Gary 2011-04-04 15:20:51

+0

OP可能想要做計算,包括計數雖然(像百分比)編輯:顯然不是從上面的評論所以+1。 – 2011-04-04 15:21:22

2

創建一個子查詢,幷包括在主查詢的結果

select 
     year(date_entered) as Yr, 
     count(*) as Cnt, 
     t.MySum 
from 
     i  
INNER JOIN (
      SELECT 
        SUM(MyColumn) as MySum 
      FROM 
        i     
      WHERE 
        code='12A' 
      ) t 
ON 
     t.ID = MyTable.ID 
where 
     code = '12A' 
group by 
     year(date_entered) 
order by 
     Yr desc 
3
;WITH cte 
    AS (SELECT YEAR(date_entered) AS yr, 
       COUNT(*)   AS cnt 
     FROM i 
     WHERE code = '12A' 
     GROUP BY YEAR(date_entered)) 
SELECT yr, 
     cnt, 
     SUM(cnt) OVER() AS totcnt 
FROM cte 
ORDER BY yr DESC 
+1

+1 Martin我也喜歡使用With作爲CTE的想法 – JonH 2011-04-04 15:21:12