gpt4 book ai didi

mysql - 关于使用多个 SQL GROUP BY 语句的问题

转载 作者:行者123 更新时间:2023-12-04 14:01:32 26 4
gpt4 key购买 nike

所以最终我试图显示一个投手在我的棒球联盟中赢得 Cy Young 奖的总次数,然后是他们赢得它的赛季年份,但按联盟名称排序,因为投手本可以在同一年的不同联赛中获奖。

这就是我尝试显示数据的方式:Andrew Jones (4) - 2021、2020 (18+); 2021 年(28 岁以上); 2021 (38+),因此我需要 Seasons 列吐出这样的数据:2021, 2020 (18+); 2021 年(28 岁以上); 2021 年(38 岁以上)

我有 3 个 mySQL 表(SEASON、LEAGUES、CY_YOUNG):

联赛

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

季节

| 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 |

这是我当前的 SQL 查询:


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;

Seasons 列目前显示如下:2021 (18+)、2020 (18+)、2021 (38+) 但我希望它显示像这样:2021 年、2020 年(18 岁以上); 2021 年(28 岁以上); 2021 年(38 岁以上)。我知道我很接近所以任何帮助都将不胜感激!

最佳答案

您需要 2 个聚合级别:

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;

参见 demo .

关于mysql - 关于使用多个 SQL GROUP BY 语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69932878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com