gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:47:41 26 4
gpt4 key购买 nike

我有两个表,其中包含来自不同设备的数据,我想按日期将它们合并(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的值。

谢谢

最佳答案

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

关于sql - 从2个不同的表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34372492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com