水平显示表格中的数据

Jam*_*mes 3 sqlite pivot

我有一个存储传感器数据的表(在 SQLite 中),看起来像这样;

TABLE Timestream:
idTimestream PK autoincrementing integer, 
time int not null, 
value float not null, 
idSensor integer not null FK
Run Code Online (Sandbox Code Playgroud)

一些但并非所有传感器都有匹配时间,但我只会考虑那些有匹配时间的传感器。我想要做的是将表格重新排列为以下格式,基于查询中列出的一组传感器,而不是表格中的全部:

Time Sensor1 Sensor2 etc.
Run Code Online (Sandbox Code Playgroud)

我正在考虑创建一个临时表,然后插入时间和第一列,然后对时间进行连接以进行后续查询,最后选择整个批次。但这听起来效率不高,我想知道是否有更好的方法?

Jac*_*las 5

在我看来,您正在尝试“旋转”数据,这可以通过多个 case 语句来完成:

测试数据:

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

询问:

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;
Run Code Online (Sandbox Code Playgroud)
时间 | s100 | s101 | s102
:--- | :--- | :--- | :---
1 | 0.1 | 0.2 | 0.3
2 | | 0.4 | 空值

dbfiddle在这里