小编典典

sql在一个查询中获取总数和过滤计数

sql

我想知道每个团队中有10%以上的用户百分比。当前,这需要两个查询:

SELECT COUNT(*) as winners, team FROM users WHERE points > 10 GROUP BY team

SELECT COUNT(*) as total, team FROM users GROUP BY team

我可以合而为一吗,所以得到这样的结果:

winners, total, team
5, 16, A

阅读 203

收藏
2021-04-28

共1个答案

小编典典

您可以使用Case .. When来检查points特定行的数量是否大于10,并相应地进行计数(使用Sum())。

SELECT COUNT(*) as total, 
       SUM(CASE WHEN points > 10 THEN 1 ELSE 0 END) AS winners, 
       team 
FROM users 
GROUP BY team

在MySQL中,我们可以进一步缩短它,因为Sum()函数可以简单地将条件运算符/函数的结果强制转换为0/1(分别为false / true):

SELECT COUNT(*) as total, 
       SUM(points > 10) AS winners, 
       team 
FROM users 
GROUP BY team
2021-04-28