想到打高尔夫球比赛我想计算一名球员在那里进行差点切换的次数(handicap_adjustment = -1),但我也希望包括那些没有被切断的球员。
PLAYER TABLE ...
PID Name
--- ----
1 Alan
2 Bob
3 Frank
4 Harry
5 Tom
CARD TABLE ...
PID HANDICAP_ADJUSTMENT
--- -------------------
1 -1
1 -1
2 0.2
2 0.2
2 0.2
2 0.2
3 0.2
3 0.2
4 -1
4 -1
4 -1
5 -1
RESULT I WANT IS ....
PID COUNT
--- -----
Alan 2
Bob 0
Frank 0
Harry 3
Tom 1
查询的任何想法?
我可以在牌表中获得带有handicap_adjustment = -1的pid计数,但不知道如何将其返回给玩家查询,该查询返回所有具有该计数的玩家:(
答案 0 :(得分:0)
SELECT p.name,a.count FROM players p
LEFT JOIN (SELECT pid,COUNT(*) AS count FROM handicap_adjustment GROUP BY pid WHERE handicap_adjustment = -1 ) a ON a.pid = p.pid
答案 1 :(得分:0)
您可以COUNT
使用CASE
表达式来获取总数。 CASE
仅包含HANDICAP_ADJUSTMENT = -1
:
select p.name,
count(case when HANDICAP_ADJUSTMENT = -1 then c.pid end) Total
from player p
left join card c
on p.pid = c.pid
group by p.name
或者您可以SUM()
使用CASE
来获取总数:
select p.name,
sum(case when HANDICAP_ADJUSTMENT = -1 then 1 else 0 end) Total
from player p
left join card c
on p.pid = c.pid
group by p.name
两者都给出结果:
| NAME | TOTAL |
-----------------
| Alan | 2 |
| Bob | 0 |
| Frank | 0 |
| Harry | 3 |
| Tom | 1 |