Warm tip: This article is reproduced from stackoverflow.com, please click
mysql sql sql-server

How do I count the total of number of participants in this way?

发布于 2020-03-31 22:59:10

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
Questioner
Sneezy
Viewed
22
Yogesh Sharma 2020-01-31 20:06

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;