Home > Software design >  Question on using multiple SQL GROUP BY statements
Question on using multiple SQL GROUP BY statements

Time:11-12

So ultimately I am trying to display the total number of times a pitcher has won the Cy Young award in my baseball league, and then the Season Year(s) they won it in, but sorted by League Name, since a pitcher could have won the award in different leagues in the same year.

This is how I'm trying to display the data: Andrew Jones (4) - 2021, 2020 (18 ); 2021 (28 ); 2021 (38 ), therefore I need the Seasons column to spit out the data like this: 2021, 2020 (18 ); 2021 (28 ); 2021 (38 )

I have 3 mySQL tables (SEASON, LEAGUES, CY_YOUNG):

LEAGUES

| LEAGUE_ID | LEAGUE_NAME   |
| -------- | -------------- |
| 1        | 18             |
| 2        | 28             |
| 3        | 38             |
| 4        | 48             |

SEASONS

| SEASON_ID| LEAGUE_ID      | SEASON_YEAR |
| --------   | -------------| ----------- |
| 332        | 1            |   2021    |
| 333        | 2            |   2021    |
| 334        | 3            |   2021    |
| 335        | 4            |   2021    |
| 300        | 1            |   2020    |
| 301        | 2            |   2020    |
| 302        | 3            |   2020    |
| 303        | 4            |   2020    |

CY_YOUNG

| SEASON_ID  | PLAYER_NAME    | PLACE     |
| --------   | -------------- | ----------|
| 332        | Andrew Jones   |   1       |
| 332        | Mike Smith     |   2       |
| 333        | Andrew Jones   |   1       |
| 333        | Jacob Grimes   |   2       |
| 334        | Andrew Jones   |   1       |
| 334        | Travis Deane   |   2       |
| 300        | Andrew Jones   |   1       |

Here is my current SQL query:


   SELECT PLAYER_NAME, COUNT(ID) AS TotalWins, GROUP_CONCAT(DISTINCT CONCAT(S.SEASON_YEAR,' (',L.LEAGUE_NAME) 
   ORDER BY S.SEASON_YEAR DESC SEPARATOR '), ') AS Seasons
   FROM CY_YOUNG
   JOIN SEASONS S ON S.SEASON_ID = CY_YOUNG.SeasonID
   JOIN LEAGUES L ON L.LEAGUE_ID = S.LEAGUE_ID
   WHERE CY_YOUNG.Place = 1
   GROUP BY PLAYER_NAME
   HAVING TotalWins > 1
   ORDER BY TotalWins DESC;  

The Seasons column currently spits out like this: 2021 (18 ), 2020 (18 ), 2021 (38 ) but I would like it to spit out like this: 2021, 2020 (18 ); 2021 (28 ); 2021 (38 ). I know I'm close so any help is appreciated!

CodePudding user response:

You need 2 levels of aggregation:

SELECT PLAYER_NAME, 
       SUM(counter) AS TotalWins,  
       GROUP_CONCAT(years, ' (', LEAGUE_NAME, ')' ORDER BY LEAGUE_NAME, years) AS Seasons
FROM (
  SELECT PLAYER_NAME, L.LEAGUE_NAME,
         COUNT(*) counter,
         GROUP_CONCAT(S.SEASON_YEAR ORDER BY S.SEASON_YEAR DESC) AS years
  FROM CY_YOUNG C
  JOIN SEASONS S ON S.SEASON_ID = C.SEASON_ID
  JOIN LEAGUES L ON L.LEAGUE_ID = S.LEAGUE_ID
  WHERE C.Place = 1
  GROUP BY C.PLAYER_NAME, L.LEAGUE_NAME
) t  
GROUP BY PLAYER_NAME
HAVING TotalWins > 1
ORDER BY TotalWins DESC; 

See the demo.

  • Related