简体   繁体   中英

Select COUNT of MAX in MySQL

I have two tables: Score table and Teams table . They both contain some foreign keys from other tables, but in my case I don't need columns from other tables.

I want to get the team id and points in a SELECT query . The points are made from a 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

As you can see a team have a tournament_id foreign key from a Tournaments table and Score table have a round_id foreign key from a Rounds table but I don't need these details in this step.

As you can see in Score table , for a round there are two records, one for each team that plays in that round and I want to know for any team how many times did it won a round (that's why I'm guessing I need a COUNT of MAX).

My SELECT query that I tried:

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

But this query it throw me the Error Code: 1111. Invalid use of group function .

Expected result:

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

How am I supposed to get to the desired result?

Thank you for your time, If something is unclear or there should be more details, let me know!

If I understand correctly you can try OUTER JOIN with subquery which get max score by each 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM