MySQL子查询在一行上列出信息

时间:2012-05-07 05:30:13

标签: mysql sql pivot

我正在尝试查询以在一行上显示事件奖品的所有数据。例如,这是我的表的一个例子。

Event_id    Place    Money
101         1        120
101         2        60
101         3        30
102         1        100
102         2        50
102         3        25

我想要的是结果如下所示:

Event_id    First    Second    Third
101         120      60        30
102         100      50        25

非常感谢任何帮助实现这一目标。

2 个答案:

答案 0 :(得分:4)

希望这有帮助。

SELECT    Event_ID,
          GROUP_CONCAT(IF(place = 1, `money`, NULL)) `First`,
          GROUP_CONCAT(IF(place = 2, `money`, NULL)) `Second`,
          GROUP_CONCAT(IF(place = 3, `money`, NULL)) `Third`
FROM      tableName
GROUP BY  event_id

如果您想了解有关sql技巧的更多信息,请访问:

Common but Useful MySQL Queries

SEE on SQLFiddle

答案 1 :(得分:0)

这对我也有用

SELECT DISTINCT Event_id, (SELECT Money FROM PRIZE WHERE Place=1 AND Event_id=t.Event_id) AS First,
(SELECT Money  FROM PRIZE WHERE Place=2 AND Event_id=t.Event_id) AS Second,
(SELECT Money FROM PRIZE WHERE Place=3 AND Event_id=t.Event_id) AS Third
FROM PRIZE t;