0

考虑到高尔夫比赛,我想计算一个球员有多少次让分盘被削减(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 计数,但不确定如何将其返回给玩家查询,该查询返回所有玩家的计数:(

4

2 回答 2

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
于 2013-01-20T22:43:40.870 回答
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

请参阅带有演示的 SQL Fiddle

或者您可以使用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

请参阅带有演示的 SQL Fiddle

两者都给出结果:

|  NAME | TOTAL |
-----------------
|  Alan |     2 |
|   Bob |     0 |
| Frank |     0 |
| Harry |     3 |
|   Tom |     1 |
于 2013-01-20T22:54:09.290 回答