我如何计算这种方式的参与者总数?
Posted
技术标签:
【中文标题】我如何计算这种方式的参与者总数?【英文标题】:How do I count the total of number of participants in this way? 【发布时间】:2020-01-31 11:51:52 【问题描述】:如果我在表格中有这些值:
Description | number of participants | GroupId
------------------------------------------
Alpha 1 34
Beta 1 34
Beta 3 34
Beta 3 34
Charlie 1 34
Charlie 2 34
如何查询才能得到这个结果?
Alpha 11 34
Beta 11 34
Beta 11 34
Beta 11 34
Charlie 11 34
Charlie 11 34
这应该代表相同Id的参与者总数
我正在尝试的 SQL 查询:
SELECT description
,COUNT(1) AS Cnt
FROM Table1
GROUP BY description
UNION ALL
SELECT 'SUM' description
,COUNT(1)
FROM Table1
【问题讨论】:
mysql
或 SQL Server
?
【参考方案1】:
您可以将sum()
与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;
但是,在SQL Server
中,您可以使用rollup
:
SELECT ISNULL(description, 'SUM') AS description, COUNT(1) as Cnt
FROM Table1
GROUP BY description WITH ROLLUP;'
根据您正在寻找的示例输出 window 函数:
select description, SUM(number_of_participants) OVER (PARTITION BY groupId), groupId
from Table1;
如果窗口功能不支持,您可以使用子查询:
select t.description,
(select sum(t1.number_of_participants)
from table1 t1
where t1.groupid = t.groupid
), t.groupid
from Table1 t;
【讨论】:
【参考方案2】:如果您想要预期输出中提到的所有行的总和,可以使用SUM() over()
窗口函数。
SELECT description,
SUM(number_of_participants) OVER () as Total,
groupId
from your_table.
输出:
+-------------+-------+---------+
| descritpion | total | groupId |
+-------------+-------+---------+
| Alpha | 11 | 34 |
| Beta | 11 | 34 |
| Beta | 11 | 34 |
| Beta | 11 | 34 |
| Charlie | 11 | 34 |
| Charlie | 11 | 34 |
+-------------+-------+---------+
如果您需要每个描述的总和,则使用SUM() OVER (PARTITION BY )
SELECT description,
SUM(number_of_participants) OVER (partition by description) as Total,
groupId
from your_table.
输出:
+-------------+-------+---------+
| descritpion | total | groupId |
+-------------+-------+---------+
| Alpha | 1 | 34 |
| Beta | 7 | 34 |
| Beta | 7 | 34 |
| Beta | 7 | 34 |
| Charlie | 3 | 34 |
| Charlie | 3 | 34 |
+-------------+-------+---------+
【讨论】:
【参考方案3】:在 SQL Server 中,可以使用GROUPING SETS
:
SELECT COALESCE(description, 'SUM'), COUNT(1) as Cnt
FROM Table1
GROUP BY GROUPING SETS ( (description), () );
【讨论】:
以上是关于我如何计算这种方式的参与者总数?的主要内容,如果未能解决你的问题,请参考以下文章