如何在SQL Server中对计数值求和?
我有表1.我想总结计数值。
怎么做?
SELECT Top 10 count(d.name) as countname,d.name as name ,sum(count(d.name)) as sumcount
FROM table 1 as d
group by d.name order by count(d.name) desc
我想显示countname
,name
,sumcount
。怎么做?
答案 0 :(得分:4)
我不确定我是否理解您的问题,但如果您只想获得所有count(d.name)
值的总和,那么这样就可以为您做到:
select sum(countname) as TotalCount
from
(
SELECT Top 10
count(d.name) as countname,
d.name as name
FROM [table 1] as d
group by d.name
order by count(d.name) desc
)a
答案 1 :(得分:2)
将with rollup
添加到查询的末尾
答案 2 :(得分:0)
扩展@Shark提供的答案,MySQL语法如下所示:
set @TotalCount = (select sum(countname) from (
select count(d.name) as countname, d.name as name
from table 1 as d
group by name
order by countname desc
limit 10
) a);
select count(d.name) as countname, d.name as name, @TotalCount
FROM table 1 as d
group by name
order by countname desc
limit 10;
您可能需要查找MS SQL语法来设置局部变量和限制。