我想知道每个团队中有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
您可以使用Case .. When来检查points特定行的数量是否大于10,并相应地进行计数(使用Sum())。
Case .. When
points
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