我在数据库中有一个表格如下:
我正在尝试创建查询,它给我的结果如下:
当我在论坛中搜索时,我确实找到了使用聚合函数和/或使用预定义语句将行转换为列的信息。从我发现的例子我发现我确实尝试了以下查询但是它们不起作用我不明白它们是如何工作的所以我只是复制查询。我确实试图在其中使用我的数据:
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
最后我的问题是我的查询必须是什么样的,我还需要一些解释它是如何工作的。
答案 0 :(得分:1)
第二个非常接近:
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
也一样。
答案 1 :(得分:0)
这post可能具有良好的洞察力和解释力。看起来您正在尝试创建数据透视表。