SQL:聚合&将行转置为列

时间:2014-08-12 11:48:46

标签: sql

我正在尝试将数据从第一个表转置到第二个表。

原始数据(汽车和州的数量有限):

+----+----------+-------+--------+
| id | car      | state | tstamp |
+----+----------+-------+--------+
| 01 | toyota   |   new | 1900   |
| 02 | toyota   |   old | 1950   |
| 03 | toyota   | scrap | 1980   |
| 04 | mercedes |   new | 1990   |
| 05 | mercedes |   old | 2010   |
| 06 | tesla    |   new | 2013   |
+-----+---------------+----------+

查询结果:

+----------+------+------+-------+
| car      | new  | old  | scrap |
+----------+------+------+-------+
| toyota   | 1900 | 1950 | 1980  |
| mercedes | 1990 | 2010 | null  |
| tesla    | 2013 | null | null  |
+----------+------+------+-------+

我的SQL技能有些生疏,因此我将不胜感激任何帮助!

1 个答案:

答案 0 :(得分:1)

这样的事情会起作用,具体取决于数据的组织方式:

SELECT
    car,
    MAX(CASE WHEN state = 'new' THEN tstamp END) AS new,
    MAX(CASE WHEN state = 'old' THEN tstamp END) AS old,
    MAX(CASE WHEN state = 'scrap' THEN tstamp END) AS scrap
FROM
    table
GROUP BY
    car;