如何在SQL Server中使用SUM而不是GROUP BY?

时间:2017-09-29 19:26:50

标签: sql sql-server sql-server-2008

我目前有:

SELECT Name, COUNT(*) as Total
FROM DataTable
WHERE Name IN ('A', 'B', 'C')
GROUP BY Name

结果输出:

Name    Total
--------------
 A        2
 B        5
 C        3

相反,我想要这个:

Name    Total
--------------
 A        10
 B        10
 C        10

这里10总共2 + 5 + 3(名称= A / B / C的记录总数)

我该怎么做?

3 个答案:

答案 0 :(得分:7)

要获得所需的结果,您可以在分组的SUM() OVER ()上使用COUNT(*)Demo

SELECT Name, 
       SUM(COUNT(*)) OVER () as Total
FROM DataTable
WHERE Name IN ('A', 'B', 'C')
GROUP BY Name

答案 1 :(得分:4)

摆脱group by并使用distinct

select distinct Name, count(*) over() as Total
from t
where name in ('A', 'B', 'C')

rextester演示:http://rextester.com/WDMT68119

返回:

+------+-------+
| name | Total |
+------+-------+
| A    |    10 |
| B    |    10 |
| C    |    10 |
+------+-------+

答案 2 :(得分:1)

如果计算所有记录,然后对所有不同的名称进行交叉连接

SELECT a.NAME
    ,x.Total
FROM DataTable a
CROSS JOIN (
    COUNT(*) AS Total FROM DataTable
    ) x
GROUP BY a.NAME
    ,x.Total