2015-02-23 161 views
0

我有一個table1,我在努力嘗試獲取類似於table2的輸出 。有任何想法嗎 ?MYSQL根據列字符串將值拆分爲多個列

表1

+-----+-----------+------+----------+---------------------+ 
| id | Sensor | Temp | Humidity | DateTime   | 
+-----+-----------+------+----------+---------------------+ 
| 1 | Sens1  | 9.7 |  55 | 2015-02-21 11:29:47 | 
| 2 | Sens2  | 4.4 |  99 | 2015-02-21 11:45:00 | 
| 3 | Sens1  | 9.8 |  56 | 2015-02-21 11:44:59 | 
| 4 | Sens2  | 4.5 |  98 | 2015-02-21 11:59:24 | 
+-----+-----------+------+----------+---------------------+ 

輸出想要的東西: 表2

+---------------------+-----------+----------+-----------+----------+ 
| Datetime   | Sens1temp | Sens1hum | Sens2temp | Sens2hum | 
+---------------------+-----------+----------+-----------+----------+ 
| 2015-02-21 11:29:47 |  9.7 |  55 | null | null | 
| 2015-02-21 11:45:00 |  null |  null |  4.4 |  99 | 
| 2015-02-21 11:44:59 |  9.8 |  56 | null | null | 
| 2015-02-21 11:59:24 |  null |  null |  4.5 |  98 | 
+---------------------+-----------+----------+----------+-----------+ 

我已經花了幾個小時尋找,但只是無法得到它的工作。

回答

1

試試這個:在SQL Fiddle

SELECT Datetime, 
     CASE WHEN Sensor='Sens1' THEN Temp END AS Sens1temp, 
     CASE WHEN Sensor='Sens1' THEN Humidity END AS Sens1hum, 
     CASE WHEN Sensor='Sens2' THEN Temp END AS Sens2temp, 
     CASE WHEN Sensor='Sens2' THEN Humidity END AS Sens2hum 
FROM TableName 
GROUP BY Datetime 

樣的結果。

+1

這裏我們不需要MAX :) CASE就夠了imho – Alex 2015-02-23 19:37:47

+0

@Alex:是的!對!更新了我的答案。 – 2015-02-23 19:40:56