将行转换为mysql

时间:2015-07-08 12:46:48

标签: mysql

我在数据库中有一个表格如下:

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

最后我的问题是我的查询必须是什么样的,我还需要一些解释它是如何工作的。

2 个答案:

答案 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可能具有良好的洞察力和解释力。看起来您正在尝试创建数据透视表。