T-SQL-包括单个查询中的计数总和(*)

时间:2011-04-04 15:13:21

标签: sql sql-server-2005 tsql

使用表i和字段date_entered和代码,我写了一个查询来列出每年代码='12A'的计数。

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变量的总和。我知道如何使用单独的查询查找总和,但我想计算原始查询中的总和。

3 个答案:

答案 0 :(得分:12)

WITH ROLLUP子句之后将GROUP BY添加到查询中,您将获得一个包含最终总数的NULL 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

答案 1 :(得分: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  

答案 2 :(得分: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