简体   繁体   中英

SELECT COUNT() INSIDE A SELECT MAX() SQL

I've got this table called player_mast in a db (data are just an example), and I want to find the club which supplied the most number of players to the 2016 EURO cup.

player_id country_id jersey_no player_name posi_to_play dt_of_bir age playing_club
1231 1231 10 Hazard striker 2/3/1991 33 Chelsea

Why this query doesn't work? It seems right to me:

SELECT playing_club, MAX(NumberOfPlayerForTeam)
FROM (
  SELECT playing_club, COUNT(player_id) AS NumberOfPlayerForTeam
  FROM player_mast
  GROUP BY(playing_club))
GROUP BY(playing_club);

Try this

SELECT playing_club, NumberOfPlayerForTeam<br>
FROM (<br>
  SELECT playing_club, COUNT(player_id) AS NumberOfPlayerForTeam<br>
  FROM player_mast<br>
  GROUP BY(playing_club))<br>
ORDER BY NumberOfPlayerForTeam DESC LIMIT 1;

If you want the playing clubs that have the most rows in your table, you can use rank() :

SELECT pm.*
FROM (SELECT playing_club, COUNT(*) AS NumberOfPlayerForTeam,
             RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM player_mast
      GROUP BY playing_club
     ) pm
WHERE seqnum = 1;

Note:

  • COUNT(<column name>) counts the number of non- NULL values in the column. There is no need to do this additional check; COUNT(*) does what you want.
  • Parentheses are not needed around the GROUP BY keys.

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