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

时间:2018-10-24 13:52:34

标签: mysql 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

3 个答案:

答案 0 :(得分:1)

尝试一下,它只是在不过滤where子句中的整个数据集的情况下使用。

SELECT COUNT(*) as total    
, SUM(case when points > 10 then 1 else 0 end) as winners
, team 
FROM users 
GROUP BY team

还可以:

SELECT COUNT(*) as total    
, COUNT(case when points > 10 then 1 else NULL end) as winners
, team 
FROM users 
GROUP BY team

答案 1 :(得分: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

答案 2 :(得分:0)

您可以尝试以下方式

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

或者您可以在以下情况下使用大小写

SELECT team, COUNT(*) as total , 
       count(CASE WHEN points > 10 THEN 1 end) AS winners  

FROM users 
GROUP BY team