If I have these values in a table:
Description | number of participants | GroupId
------------------------------------------
Alpha 1 34
Beta 1 34
Beta 3 34
Beta 3 34
Charlie 1 34
Charlie 2 34
How can I query to get this result?
Alpha 11 34
Beta 11 34
Beta 11 34
Beta 11 34
Charlie 11 34
Charlie 11 34
This is supposed to represent the total number of participants for the same Id
SQL query I am trying:
SELECT description
,COUNT(1) AS Cnt
FROM Table1
GROUP BY description
UNION ALL
SELECT 'SUM' description
,COUNT(1)
FROM Table1
You can use sum()
with subquery
:
SELECT description, COUNT(1) as Cnt
FROM Table1
GROUP BY description
UNION ALL
SELECT 'SUM', SUM(Cnt)
FROM (SELECT COUNT(1) AS Cnt
FROM Table1
GROUP BY description
) C;
However, in SQL Server
you can use rollup
:
SELECT ISNULL(description, 'SUM') AS description, COUNT(1) as Cnt
FROM Table1
GROUP BY description WITH ROLLUP;'
Based on sample output you are looking for window function :
select description, SUM(number_of_participants) OVER (PARTITION BY groupId), groupId
from Table1;
You can use sub-query if window function not supports :
select t.description,
(select sum(t1.number_of_participants)
from table1 t1
where t1.groupid = t.groupid
), t.groupid
from Table1 t;
Thank you, using window function solved my issue