转换SQL查询结果的表结构(pivot)

时间:2015-02-13 10:18:49

标签: mysql pivot

我有一个来自查询的表,其中包含以下内容结构:

+-----+-----------+-------+
|date | sensor_id | power |
+-----+-----------+-------+
|date1|     1     |  0.51 |
|date1|     2     |  0.52 |
|date1|     3     |  0.53 |
|date2|     1     |  0.61 |
|date2|     2     |  0.61 |
|date2|     3     |  0.63 |
|date3|     1     |  0.71 |
|date3|     2     |  0.72 |
|date3|     3     |  0.73 |
+-----+-----------+-------+

有没有办法使用SQL将此表转换为以下内容?

+-----+-----------+------------+-----------+
|date |    1      |     2      |     3     |
+-----+-----------+------------+-----------+
|date1|  0.51     |    0.52    |   0.53    |
|date1|  0.61     |    0.62    |   0.63    |
|date1|  0.71     |    0.72    |   0.73    |
+-----+-----------+------------+-----------+

3 个答案:

答案 0 :(得分:1)

如果您事先知道sensor_id的可能值集合,则可以使用条件聚合来执行数据透视:

select 
  date,
  max(case when sensor_id = 1 then power else 0 end) as "1",
  max(case when sensor_id = 2 then power else 0 end) as "2",
  max(case when sensor_id = 3 then power else 0 end) as "3"
from Table1
group by date;

如果您不了解所有可能的值,可以使用动态SQL来构建适当的语句;该查询特定于MySQL:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(
    DISTINCT CONCAT(
      'MAX(CASE WHEN sensor_id = ',
      sensor_id,' 
      THEN power ELSE 0 END) AS "', 
      sensor_id,'"'
    )
  ) INTO @sql FROM Table1;

SET @sql = CONCAT(
  'SELECT date, ', 
  @sql, 
  ' FROM Table1 GROUP BY date'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

有关示例,请参阅此SQL Fiddle

答案 1 :(得分:0)

是的,这是可能的,并且是calles" Pivot" 检查一下.. Pivot in Mysql

答案 2 :(得分:-3)

select * 
from table
group by sensor_id