用于显示分组列和其他具有特定值的列的SQL命令

时间:2013-03-26 13:44:36

标签: sql select group-by

我有下表:

+---------+------+------------+
|Player   |Game  |Status      |
+---------+------+------------+
|Player01 |GameA |uncompleted |
|Player02 |GameA |uncompleted |
|Player03 |GameC |completed   |
|Player04 |GameA |uncompleted |
|Player05 |GameB |completed   |
|Player06 |GameB |completed   |
|Player07 |GameA |uncompleted |
|Player08 |GameA |completed   |
|Player09 |GameC |uncompleted |
|Player10 |GameB |completed   |
|Player11 |GameB |uncompleted |
|Player12 |GameA |completed   |
.....
+---------+------+------------+

并希望显示每场比赛完成比赛的球员数量和球员数量:

+------+-----------------+----------+
|Game  |Number of Players|Completed |
+------+-----------------+----------+
|GameA | 6               | 2        |
|GameB | 4               | 3        |
|GameC | 2               | 1        |
...
+------+-----------------+----------+

执行该任务的最简单的SQL select命令是什么? 谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个

select Game , count(*) NumPlayers,
sum(case when status = 'completed' then 1 else 0 end) completed 
from table
group by game

答案 1 :(得分:0)

您需要条件求和:

select game, count(distinct Player) as NumPlayers,
       sum(case when status = completed then 1 else 0 end) as Status
from t
group by game