如何实现组合多个COUNT()和GROUP BY的MySQL Query

时间:2015-05-29 01:05:52

标签: mysql sql select count

所以我有这种类型的数据:

id      date            user_id    result
1       2015-05-04      1          win
2       2015-05-06      1          loss
3       2015-05-09      2          loss
4       2015-05-10      2          win
5       2015-05-16      1          win

我需要按照大多数胜利排序前四名用户。但我还需要获得这4位最佳获胜者的损失数量。因此,当我查询这个特定的集合时,我得到了这个:

user    wins    losses
1       2       1
2       1       1

我知道如何通过使用:

获得与user_id一起的胜利
SELECT user_id, COUNT(id) AS wins FROM table WHERE result = 'win' GROUP BY user_id ORDER BY COUNT(id) DESC LIMIT 4

但是我如何使用相同的查询获得前4名玩家的损失呢?我知道这是可能的,但只是不知道如何执行它!有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您想要条件聚合:

SELECT user_id, sum(result = 'win') AS wins, sum(result = 'loss') as losses
FROM table
GROUP BY user_id
ORDER BY wins DESC
LIMIT 4;

答案 1 :(得分:0)

我会这样做:

SELECT user_id, 
  SUM(CASE WHEN result='win' THEN 1 ELSE 0 END) AS wins,
  SUM(CASE WHEN result='loss' THEN 1 ELSE 0 END) AS losses 
FROM table1 
GROUP BY user_id 
ORDER BY wins DESC
LIMIT 4

小提琴在这里:http://sqlfiddle.com/#!9/00ac7/8