sql - 如何对值进行分组?

时间:2017-12-15 18:36:04

标签: mysql sql mariadb pivot-table

我有一张桌子:

> SELECT * FROM tempLog WHERE DATE(ts) = CURDATE() LIMIT 9;

+-------+---------------------+----------+-------+-------+
| id    | ts                  | sensorid | value | event |
+-------+---------------------+----------+-------+-------+
| 11020 | 2017-12-15 00:00:01 |        3 |  18.1 | cron  |
| 11021 | 2017-12-15 00:00:01 |        4 |  14.8 | cron  |
| 11022 | 2017-12-15 00:00:01 |        5 |   1.3 | cron  |
| 11023 | 2017-12-15 00:02:02 |        3 |  18.1 | cron  |
| 11024 | 2017-12-15 00:02:02 |        4 |  14.8 | cron  |
| 11025 | 2017-12-15 00:02:02 |        5 |   1.3 | cron  |
+-------+---------------------+----------+-------+-------+

是否有可能构建一个查询,所以我得到

+---------------------+---------+---------+---------+
| ts                  | sensor3 | sensor4 | sensor5 |
+---------------------+---------+---------+---------+
| 2017-12-15 00:00:01 |   18.1  |   14.8  |  1.3    |
| 2017-12-15 00:02:02 |   18.1  |   14.8  |  1.3    |
+---------------------+---------+---------+---------+

即,选择所有不同的时间戳'并在那时从不同的传感器获取每个值。

传感器将在以后更多,所以我必须考虑到这一点。 他们都将在相同的时间戳上进行民意调查。

由于 /乔恩

1 个答案:

答案 0 :(得分:1)

select ts, 
       max(case when sensorid = 3 then value else 0 end) as sensor3,
       max(case when sensorid = 4 then value else 0 end) as sensor4,
       max(case when sensorid = 5 then value else 0 end) as sensor5
from your_table
group by ts