时间序列表的sql并集,忽略/删除重复项

nwnhqdif  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(235)

我在找一些关于postgresql查询的帮助。我有两个表中的子查询,两个表都有相同的所有列,但两个表中的数据可能不同:
tab1(有时可能为空,因为子查询中不满足条件语句)

+---------+------------+
|   ts    | value      |
+---------+------------+
| 1       | 1002       |
| 2       | 3234       |
| 3       | 530        |
| 4       | 340        |
+---------+------------+

tab2(总是有数据)

+---------+------------+
|   ts    | value      |
+---------+------------+
| 1       | 1303       |
| 2       | 9000       |
| 3       | 4003       |
| 4       | 924        |
| 5       | 225        |
| 6       | 346        |
+---------+------------+

我需要用tab2值扩展tab1。因此,如果两个表中的ts(时间步长)相同,我将它们连接起来并丢弃重复的行。我想到了这个:
使用my\u select as(select ts,value,from tab1)select*from my\u select union all select ts,value from tab2 where and ts>(选择max(ts)from my\u select)

+---------+------------+
|   ts    | value      |
+---------+------------+
| 1       | 1002       |
| 2       | 3234       |
| 3       | 530        |
| 4       | 340        |
| 5       | 225        |
| 6       | 346        |
+---------+------------+

显然,这种连接只有在第一个表有数据时才起作用,否则max(ts)失败并且没有数据出现。理想情况下,在这种情况下,如果没有tab1数据可用,我只希望返回tab2数据。请问有没有更优雅的解决方案?

mccptt67

mccptt671#

我想你可以用它做你想做的事 union all 以及 not exists :

select ts, value
from tab1
union all
select t1, value
from tab2
where not exists (select 1 from tab1 where tab1.ts = tab2.ts);

相关问题