MySQL pivot / crosstab

时间:2014-10-02 09:43:28

标签: mysql sql crosstab

我有下表

date_time,channel_code,value
"2013-09-30 08:50:00",no,0.01
"2013-09-30 08:50:00",no2,0.57
"2013-09-30 08:50:00",nox,0.58
"2013-09-30 09:00:00",no,0.03
"2013-09-30 09:00:00",no2,0.59
"2013-09-30 09:00:00",nox,0.62
"2013-09-30 09:10:00",no,0.03
"2013-09-30 09:10:00",no2,0.63
"2013-09-30 09:10:00",nox,0.66
"2013-09-30 09:20:00",no,0.02
"2013-09-30 09:20:00",no2,0.65
"2013-09-30 09:20:00",nox,0.68
"2013-09-30 09:30:00",no,0.04
"2013-09-30 09:30:00",no2,0.74
"2013-09-30 09:30:00",nox,0.78

我试图以下列形式获取数据:

date_time,no,no2,nox
"2013-09-30 08:50:00",0.01,057,0.58
到目前为止没有运气。数据库是MySQL,我在这里读到它没有PIVOT功能。我也看过类似的帖子(比如this),但我想我的SQL技能只带我这么远: - )

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:2)

您可以编写动态数据透视查询,如下所示

SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
  CONCAT('MAX(CASE WHEN channel_code = ''',
         channel_code, 
         ''' THEN value  END) `',
         channel_code,'`'
         )
          ORDER BY date_time,channel_code ASC        
 )
  INTO @sql
  FROM test;

SET @sql = CONCAT('SELECT date_time, ', @sql, ' 
                     FROM test
                    GROUP BY date_time');

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

Demo

如果您有限制/确定channel_code然后

,那么它很简单
SELECT
date_time,
MAX(CASE WHEN channel_code = 'no' THEN value  END) `no`,
MAX(CASE WHEN channel_code = 'no2' THEN value  END) `no2`,
MAX(CASE WHEN channel_code = 'nox' THEN value  END) `nox`
FROM test
GROUP BY date_time

Demo