Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SUM over GROUP BY in SQL Server?

I currently have:

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

Resulting output:

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

Instead I want this:

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

Here 10 is a total of 2 + 5 + 3 (total number of records with name = A/B/C)

How do I do this?

like image 256
Quick-gun Morgan Avatar asked Nov 18 '25 07:11

Quick-gun Morgan


2 Answers

To get your desired result you can use SUM() OVER () on the grouped COUNT(*). Demo

SELECT Name, 
       SUM(COUNT(*)) OVER () as Total
FROM DataTable
WHERE Name IN ('A', 'B', 'C')
GROUP BY Name
like image 134
Martin Smith Avatar answered Nov 20 '25 22:11

Martin Smith


Get rid of the group by and use distinct:

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

rextester demo: http://rextester.com/WDMT68119

returns:

+------+-------+
| name | Total |
+------+-------+
| A    |    10 |
| B    |    10 |
| C    |    10 |
+------+-------+
like image 43
SqlZim Avatar answered Nov 20 '25 20:11

SqlZim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!