gpt4 book ai didi

mysql - 将行转换为mysql中的列

转载 作者:行者123 更新时间:2023-11-29 02:55:15 25 4
gpt4 key购买 nike

我在数据库中有一个表,如下所示:

enter image description here

我正在尝试创建查询,结果如下:

enter image description here

当我在论坛中搜索时,我确实找到了有关使用聚合函数和/或使用预定义语句将行转换为列的信息。从示例中我发现我确实尝试了以下查询但是它们不起作用我不明白它们是如何工作的所以我只是复制查询。我确实尝试在其中使用我的数据:

select fk_playerID as name, roundID as roundNo, score
from(
roundID,
CASE WHEN roundID = 1 THEN score END AS 1,
CASE WHEN roundID = 2 THEN score END AS 2,
CASE WHEN roundID = 3 THEN score END AS 3,
from cup
) cup group by fk_playerID

第二个:

SELECT fk_playerID as name, roundID as roundNo, score
MAX(CASE WHEN'roundID' = 1, THEN score end) roundNo1,
MAX(CASE WHEN'roundID' = 2, THEN score end) roundNo2,
MAX(CASE WHEN'roundID' = 3, THEN score end) roundNo3
FROM cup
ORDER BY fk_playerID

最后我的问题是我的查询应该是什么样子,我还需要一点解释它是如何工作的。

最佳答案

第二个非常接近:

SELECT c.fk_playerID,
p.Name
MAX(CASE WHEN c.roundID = 1 THEN c.score END) AS roundNo1,
MAX(CASE WHEN c.roundID = 2 THEN c.score END) AS roundNo2,
MAX(CASE WHEN c.roundID = 3 THEN c.score END) AS roundNo3
FROM cup c
JOIN Player p on c.fk_playerID = p.ID
GROUP BY c.fk_playerID, p.Name

您正在按 fk_playerID 分组。让我们考虑 player = 1。这个

CASE WHEN roundID = 1 THEN score END 

将为 score 生成以下集合:{1, null, null}。 Max 将返回 1。

CASE WHEN roundID = 2 THEN score END 

将为 score 生成以下集合:{null, 1, null}。 Max 将返回 1。

CASE WHEN roundID = 3 THEN score END 

将为 score 生成以下集合:{null, null, 1}。 Max 将返回 1。

同样适用于 player = 19

关于mysql - 将行转换为mysql中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31293170/

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