1

我的 mySQL 有问题。我有一张这样的桌子:

Time                    Sensor    Value   
2012-10-16 14:42:32 VI0    0      
2012-10-16 14:42:32 VI1    0      
2012-10-16 14:42:32 VI2    0      
2012-10-16 14:42:32 VI3    0      
2012-10-16 14:42:33 VI0    1      
2012-10-16 14:42:33 VI1    1      
2012-10-16 14:42:33 VI2    1      
2012-10-16 14:42:33 VI3    1    

我有一个表“ sensor”,其中包含所有名称传感器和其他信息。是否可以在这样的表中重新排列该表:

Time                    VI0        VI1      VI2    VI3

2012-10-16 14:42:32 0      0         0      0

2012-10-16 14:42:32 1      1         1      1

我正在查看数据透视表,但我不知道它是否正确。

PS也许我找到了解决方案:

SELECT time,GROUP_CONCAT(value) as Sensor FROM measure2 GROUP BY time;

时间 GROUP_CONCAT(值)

2012-10-16 14:42:32 0,0,0,0

我可以用逗号代替 GROUP_CONCAT 写传感器的名称吗?

4

1 回答 1

3

在我看来,您需要pivot动态地对数据使用准备好的语句。这将使用带有CASE语句的聚合函数:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when Sensor = ''',
      Sensor,
      ''' then value end) AS ',
      Sensor
    )
  ) INTO @sql
FROM  measure2;

SET @sql = CONCAT('SELECT time, ', @sql, ' 
                  FROM measure2 
                  GROUP BY time');

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

请参阅带有演示的 SQL Fiddle

如果您有已知的值,那么您可以对这些值进行硬编码:

select time,
  max(case when sensor = 'VI0' then value end) as VI0,
  max(case when sensor = 'VI1' then value end) as VI1,
  max(case when sensor = 'VI2' then value end) as VI2,
  max(case when sensor = 'VI3' then value end) as VI3
from measure2
group by time

请参阅带有演示的 SQL Fiddle

于 2012-10-30T12:12:00.200 回答