简体   繁体   English

MySQL数据透视/交叉表

[英]MySQL pivot / crosstab

I have the following table 我有下表

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

I am trying to get the data in the following form: 我正在尝试以以下形式获取数据:

date_time,no,no2,nox
"2013-09-30 08:50:00",0.01,057,0.58

with no luck so far. 到目前为止没有运气。 The database is MySQL, I've read here that it does not have a PIVOT function. 该数据库是MySQL,我在这里已经阅读到它没有PIVOT函数。 Also I had a look on similar posts (like this ) but I guess my SQL skill only takes me this far :-) 我也看过类似的文章(像这样 ),但我想我的SQL技能只能带我这么远了:-)

Any help appreciated 任何帮助表示赞赏

You can write your dynamic pivot query as below 您可以如下编写动态数据透视查询

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

Or its simple if you have limited/determined channel_code then 还是简单的(如果您的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM