我有一个遇到问题的查询,涉及下面描述的 3 个表。还有更多字段对此查询无关紧要。
users:
id
display_name
matches:
id
league_seasons_id
date_played
winner_id
loser_id
players:
id
match_id
player_id
nth_match
division
result # values are "Win" or "Loss"
end_hcp
我正在尝试产生这样的输出:
Name Hcp Wins Losses High Run HR Pct of Hcp
Alan 705 12 2 27 3.83%
Bill 815 10 4 30 3.68%
Charlie 611 9 5 12 1.96%
Denise 788 8 6 15 1.90%
...
下面的查询大部分都有效,但Hcp
列除外。在玩家表中,每场比赛有 2 条记录,一条是获胜者的信息,另一条是失败者的信息。在每条记录中都有start_hcp
和end_hcp
,即球员在比赛前的差点和基于比赛的新差点。
我需要end_hcp
从每个玩家玩到现在的最后一场比赛(查询的日期/时间)。我猜会涉及一个子查询,但我还没有弄清楚它是什么。
SELECT
p.division AS Division,
u.display_name AS Name,
p.end_hcp AS Handicap,
count(if(result = "Win", 1, NULL)) AS Wins,
count(if(result = "Loss", 1, NULL)) AS Losses,
max(high_run) AS "High Run",
concat(truncate((max(high_run) * 100 / p.end_hcp), 2), '%') AS "HR Pct of Hcp"
FROM
`lwljhb_lwl_players` AS p,
`lwljhb_lwl_matches` AS m,
`lwljhb_users` AS u
WHERE
m.league_seasons_id = 9 AND
p.match_id = m.id AND
p.player_id = u.id AND
u.display_name <> "Bye"
GROUP BY u.display_name
ORDER BY p.division, Wins DESC, Losses