【问题标题】:Getting data from 2 different tables从 2 个不同的表中获取数据
【发布时间】:2015-12-19 15:44:19
【问题描述】:

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

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

餐桌温度

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

表计

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

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

Date, Dev7, Dev13, Dev14
2015-01-01, 5.2, 13200, 540
2015-01-02, 5.6, 11200, 570
2015-01-03, 5.3, 13700, 660
2015-01-04, 4.7, 14200, 590
2015-01-05, 4.9, 0, 700

这将让我按日期绘制设备 7、13 和 14 的值。

谢谢

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    您可以使用条件聚合来解决此问题 -- 在使用 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-20
      • 2020-10-23
      • 2017-07-28
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多