2012-10-30 81 views
1

我有一個mySQL的問題。 我有這樣一個表:在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 

我期待透視表,但我不知道這是否是正確的方式。

P.S.也許我找到了解決辦法:

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

時間GROUP_CONCAT(值)

二○一二年十月一十六日14時42分32秒0,0,0,0

相反GROUP_CONCAT可以謹逗號傳感器的名字?

+0

查看這些鏈接:[動態數據透視表](http://buysql.com/mysql/14-how-to-automate-pivot-tables.html),[自動化數據透視表查詢](http: //www.artfulsoftware.com/infotree/queries.php#523)。 – Devart

+0

VI0等總是零或一個或不同的值? –

+0

@MichaelBerkowski有不同的價值,是衡量的工廠 – vincenzoAlessandroSantamaria

回答

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 with Demo

如果你已經知道的值,那麼你可以硬編碼值:

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 with Demo

+0

非常感謝你! – vincenzoAlessandroSantamaria