MYSQL根据列字符串将值拆分为多个列

时间:2015-02-23 19:32:15

标签: mysql

我有一个table1,我正在努力尝试获得输出 喜欢table2。有什么想法吗?

表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 个答案:

答案 0 :(得分:1)

试试这个:

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

SQL Fiddle中的示例结果。