如何在 SQL Server 中求和计数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8753186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:52:54  来源:igfitidea点击:

How to sum count value in SQL Server?

sqlsql-server

提问by Jam Sva

How to sum count value in SQL Server ?

如何在 SQL Server 中求和计数值?

I have table 1. I want to sum count value.

我有表 1。我想求和计数值。

How to do that ?

怎么做 ?

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

I want to display countname, name, sumcount. How to do that ?

我想显示countname, name, sumcount。怎么做 ?

回答by

Not sure I'm understanding your question, but if you're just looking to get the sum of all the count(d.name)values, then this would do that for you:

不确定我是否理解您的问题,但如果您只是想获得所有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

回答by gordy

add with rollupto the end of your query

添加with rollup到查询的末尾

回答by Reuben

Expanding on the answer provided by @Shark, MySQL syntax will look like the following:

扩展@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;

You may need to look up MS SQL syntax for setting local variables and limits.

您可能需要查找 MS SQL 语法来设置局部变量和限制。