我目前有:
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的记录总数)
我该怎么做?
答案 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