从2个不同的表中获取数据

时间:2015-12-19 15:44:19

标签: sql sqlite

我有两个表包含来自不同设备的数据,我希望每个日期(YMD格式)将它们组合在一起。每个表都有多个DeviceRowId,但在本例中,我只对7,13和14感兴趣。

我正在选择一个sqlite3数据库,我会将结果导出到csv

表温度

Code

表格

DeviceRowId, Temp_Avg, Date
7, 5.2, 2015-01-01
7, 5.6, 2015-01-02
7, 5.3, 2015-01-03
7, 4.7, 2015-01-04
7, 4.9, 2015-01-05
4, 19.0, 2015-01-01
4, 19.6, 2015-01-02
4, 18.9, 2015-01-03
4, 19.1, 2015-01-04

我无法保证所有设备每天都有一个条目,因此设备13在2015-01-05没有条目。 我想要实现的是:

DeviceRowId, Value, Date
13, 13200, 2015-01-01
13, 11200, 2015-01-02
13, 13700, 2015-01-03
13, 14200, 2015-01-04
14, 540, 2015-01-01
14, 570, 2015-01-02
14, 660, 2015-01-03
14, 590, 2015-01-04
14, 700, 2015-01-05
19, 350, 2015-01-01
19, 680, 2015-01-02
19, 920, 2015-01-03
19, 310, 2015-01-04
19, 700, 2015-01-05

这将让我每个日期绘制设备7,13和14的值。

由于

1 个答案:

答案 0 :(得分:2)

使用union all将数据汇集在一起​​后,您可以使用条件聚合进行处理:

select date,
       max(case when DeviceRowId = 7 then temp_avg end) as Dev7,
       max(case when DeviceRowId = 13 then temp_avg end) as Dev13,
       max(case when DeviceRowId = 14 then temp_avg end) as Dev14
from (select Date, DeviceRowId, temp_avg
      from table1
      where DeviceRowId in (7, 13, 14)
      union all
      select Date, DeviceRowId, value
      from table2
      where DeviceRowId in (7, 13, 14)
     ) t
group by date
order by date;
相关问题