T-SQL-在单个查询中包含计数总和(*)
使用表i和date_输入的字段和code,我编写了一个查询,列出了code='12A'中每年的计数T-SQL-在单个查询中包含计数总和(*),sql,sql-server-2005,tsql,Sql,Sql Server 2005,Tsql,使用表i和date_输入的字段和code,我编写了一个查询,列出了code='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 ... 我
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变量的总和。我知道如何使用单独的查询查找总和,但我希望在原始查询中计算总和 创建子查询并将结果包含在主查询中
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
在
GROUP BY
子句之后的查询中添加WITH ROLLUP
,您将获得一个包含最终总计的带有空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
OP可能想要进行包括计数在内的计算(比如百分比)编辑:显然不是来自上面的评论so+1。为什么分组方式和不同?@Dems-我认为Joe只是在复制和粘贴。你不需要区分。我已经编辑了Joe提供的答案以显示这一点。@John:谢谢你的清理。我确实是盲目地复制/粘贴了OP的问题。谢谢你纠正了distinct的误用。我有很多东西要学。注意:查询中的
distinct
是超级棒的,因为您是按年份分组的,所有记录都已经是唯一的。@Guffa-distinct
和groupby
似乎是TSQL中最容易被误解的概念。我见过人们为了得到“正确”的数据而按20个不同的列分组(
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