我有一个MySQL表,其结构如下:
+-------------+-------+-----------+
| timestamp | value | sensor_id |
+-------------+-------+-----------+
举个例子,有三种可能的传感器ID:ID1
,ID2
和ID3
。 我想执行一个查询,以以下格式输出数据:
+-------------+-----------+-----------+-----------+
| timestamp | value_id1 | value_id2 | value_id3 |
+-------------+-----------+-----------+-----------+
只从一个ID中提取数据是很简单的,但我很难将三个ID合并在一起。
SELECT timestamp,
value AS 'value_id1'
FROM table
WHERE sensor_id='id1'
编辑以获得澄清:(timestamp
,sensor_id
)在表中是唯一的
使用条件聚合:
select
timestamp,
max(case when sensor_id = 'id1' then value end) value_id1,
max(case when sensor_id = 'id2' then value end) value_id2,
max(case when sensor_id = 'id3' then value end) value_id3
from mytable
group by timestamp