SQL:创建列(MySQL/PHPMyAdmin)

mpgws1up  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(149)

同查询:

SELECT TableA.ID, TableA.SensorID, TableA.Value, SensorIDs.Name, TableA.timestamp
FROM TableA
JOIN SensorIDs
ON TableA.SensorID = SensorIDs.ID  // column 'Name' is in 'SensorIDs'

我的结果表如下所示:

ID | SensorID | Value  | Name | timestamp
 1 |  1       |  5     |  A   |  1000
 2 |  2       |  10    |  B   |  1000
 3 |  3       |  0     |  C   |  1000
 4 |  1       |  1     |  A   |  2000
 5 |  2       |  2     |  B   |  2000
 6 |  3       |  6     |  C   |  2000
[..]

是否有办法更改我的SQL查询以获得如下表:

A | B  | C | timestamp
 5 | 10 | 0 |   1000
 1 | 2  | 6 |   2000

可能是带有GROUP BY的内容?
编辑:在可预见的未来,“名称”将只有这3个值。
编辑:RDBMS:MySQL原生(InnoDB)、PHPMyAdmin
编辑:忘记在结果中添加“传感器ID”列。

uyhoqukh

uyhoqukh1#

我找到了答案,通过创建一个PIVOT表与教程,我在这里找到:https://ubiq.co/database-blog/how-to-create-pivot-table-in-mysql/

SELECT time,
sum(IF(SensorID=1, Value, NULL)) AS Sensor1,
sum(IF(SensorID=2, Value, NULL)) AS Sensor2,
sum(IF(SensorID=3, Value, NULL)) AS Sensor3,
sum(IF(SensorID=4, Value, NULL)) AS Sensor4
FROM TableA
GROUP BY time

相关问题