Sqlite

水平顯示表格中的數據

  • March 23, 2017

我有一個儲存感測器數據的表(在 SQLite 中),看起來像這樣;

TABLE Timestream:
idTimestream PK autoincrementing integer, 
time int not null, 
value float not null, 
idSensor integer not null FK

一些但不是所有感測器都有匹配時間,但我只會考慮那些匹配時間。我想要做的是根據查詢中列出的一組感測器,而不是表中的全部感測器,將表重新排列為以下格式:

Time Sensor1 Sensor2 etc.

我正在考慮創建一個臨時表,然後插入時間和第一列,然後在時間上進行連接以進行後續查詢,最後選擇全部。這聽起來不太有效,我想知道是否有更好的方法?

在我看來,您正在嘗試“透視”數據,這可以通過多個案例語句來完成:

測試數據:

create table timestream(
  idTimestream integer primary key autoincrement
, time int not null
, value float not null
, idSensor integer not null);
insert into timestream(time, value, idSensor) values(1,0.1,100);
insert into timestream(time, value, idSensor) values(1,0.2,101);
insert into timestream(time, value, idSensor) values(1,0.3,102);
insert into timestream(time, value, idSensor) values(2,0.4,101);

詢問:

select time, sum(case idSensor when 100 then value end) as s100,
             sum(case idSensor when 101 then value end) as s101,
             sum(case idSensor when 102 then value end) as s102
from timestream
group by time;
時間 | s100 | s101 | s102
:--- | :--- | :--- | :---
1 | 0.1 | 0.2 | 0.3
2 | *空*| 0.4 | *零*

dbfiddle在這裡

引用自:https://dba.stackexchange.com/questions/30263