Select MySQL 中的 MAX 个

Select COUNT of MAX in MySQL

我有两个表:Score tableTeams table。它们都包含来自其他表的一些外键,但就我而言,我不需要来自其他表的列。

我想在 SELECT query 中获得 team id and points。积分来自 COUNT of MAX score of a team per round.

Score table:

id round_id team_id score
1085e36b-7621-4634-93e2-c5404108ed23 424d4186-4432-4b8d-ab9d-00ee71945cf6 752f9ebc-7016-42f2-be90-768711fc3d46 18
47ff3765-6357-47bc-abb8-6b5adf436546 424d4186-4432-4b8d-ab9d-00ee71945cf6 90dd8de4-8ddc-46cd-8b67-d93edbede174 7
b26b1a5b-8606-4c08-b838-30fdbcf98697 3fbb49a0-7a8a-4db5-b854-84a9ce7ac2b3 90dd8de4-8ddc-46cd-8b67-d93edbede174 20
c1add78a-94a3-48cf-b89d-4e4500ab738d 3fbb49a0-7a8a-4db5-b854-84a9ce7ac2b3 752f9ebc-7016-42f2-be90-768711fc3d46 21

Teams table:

id name tournament_id
2b56a499-9fc4-40c2-a7c4-43762c2b27e7 2@1.com & 4@1.com 9aaa6f86-5555-49b8-99a6-900a90dc3c7c
752f9ebc-7016-42f2-be90-768711fc3d46 5@1.com & 3@1.com 9aaa6f86-5555-49b8-99a6-900a90dc3c7c
7c9aa32a-ff99-4169-9512-27bc0aac0093 7@1.com & 6@1.com 9aaa6f86-5555-49b8-99a6-900a90dc3c7c
90dd8de4-8ddc-46cd-8b67-d93edbede174 8@1.com & 1@1.com 9aaa6f86-5555-49b8-99a6-900a90dc3c7c

如您所见,team have a tournament_id foreign key from a Tournaments tableScore table have a round_id foreign key from a Rounds table 但我在此步骤中不需要这些详细信息。

正如您在 Score table 中看到的那样,对于 roundtwo records, one for each team that plays in that round 我想 知道任何一支球队赢得了多少次round(这就是为什么我猜我需要 MAX 的原因)。

我试过的SELECT query

SELECT team_id, count(max(score)) as points FROM Score
WHERE team_id IN (SELECT DISTINCT t.id 
    FROM Teams t
    WHERE t.tournament_id = '9aaa6f86-5555-49b8-99a6-900a90dc3c7c')
GROUP BY round_id

但是这个 query 它给我抛出了 错误代码:1111。组函数的使用无效

预期结果:

team_id points
752f9ebc-7016-42f2-be90-768711fc3d46 2
90dd8de4-8ddc-46cd-8b67-d93edbede174 0

我应该怎样才能得到想要的结果?

感谢您的宝贵时间!如果有什么不清楚或应该有更多细节,请告诉我!

如果我理解正确,你可以尝试 OUTER JOIN 子查询每个 round_id

获得最高分数
SELECT s.team_id,
       COUNT(m_Score)
FROM Score s 
LEFT JOIN 
(
    SELECT round_id,MAX(score) m_Score
    FROM Score 
    GROUP BY round_id
) t1 ON t1.m_Score = s.Score and t1.round_id = s.round_id
WHERE team_id IN (
    SELECT t.id 
    FROM Teams t
    WHERE t.tournament_id = '9aaa6f86-5555-49b8-99a6-900a90dc3c7c'
)
GROUP BY s.team_id

sqlfiddle