Pgsql 在数据库中查找相似的记录
Pgsql find similar records in database
我有一个 table 的布局是这样的
sensor_id
time
value
1
2020-12-22 09:00:00
20.5
1
2020-12-22 10:00:00
21.5
1
2020-12-22 11:00:00
22.5
1
2020-12-22 12:00:00
23.5
2
2020-12-22 09:00:00
30.5
2
2020-12-24 10:00:00
31.5
2
2020-12-24 11:00:00
32.5
2
2020-12-24 12:00:00
33.5
我希望能够找到 sensor_id 1 和 2 具有相同日期的所有参考文献。
计划是让用户 select 一个包含传感器列表的站点,将数据从站点 a 移动到站点 b。如果a站有数据b站本次已经存在,那我就不用动了。
我计划 'moving' 数据 运行 一个简单的 update readings set sensor_id = #a where sensor_id = #b
。
注意,实际数据我有几十亿条记录,我会'moving'数据从一个sensor_id传到另一个,而且经常会有一个大约10个传感器的列表要移动一次。
我真的不知道从哪里开始。
谁能指出我正确的方向?
find all references where sensor_id 1 and 2 have the same date
为此你可以使用聚合:
select time
from readings
when sensor_id in (1, 2)
group by time
having count(*) = 2
这会为您提供两个传感器都有数据的所有 time
。
从问题的其余部分来看,我认为您想在不与现有记录冲突的情况下更改记录上的传感器 ID(例如,从 1
到 2
)。这表明:
update readings r
set sensor_id = 2
where sensor_id = 1 and not exists (
select 1 from readings r1 where r1.sensor_id = 2 and r1.time = r.time
)
我有一个 table 的布局是这样的
sensor_id | time | value |
---|---|---|
1 | 2020-12-22 09:00:00 | 20.5 |
1 | 2020-12-22 10:00:00 | 21.5 |
1 | 2020-12-22 11:00:00 | 22.5 |
1 | 2020-12-22 12:00:00 | 23.5 |
2 | 2020-12-22 09:00:00 | 30.5 |
2 | 2020-12-24 10:00:00 | 31.5 |
2 | 2020-12-24 11:00:00 | 32.5 |
2 | 2020-12-24 12:00:00 | 33.5 |
我希望能够找到 sensor_id 1 和 2 具有相同日期的所有参考文献。
计划是让用户 select 一个包含传感器列表的站点,将数据从站点 a 移动到站点 b。如果a站有数据b站本次已经存在,那我就不用动了。
我计划 'moving' 数据 运行 一个简单的 update readings set sensor_id = #a where sensor_id = #b
。
注意,实际数据我有几十亿条记录,我会'moving'数据从一个sensor_id传到另一个,而且经常会有一个大约10个传感器的列表要移动一次。
我真的不知道从哪里开始。 谁能指出我正确的方向?
find all references where sensor_id 1 and 2 have the same date
为此你可以使用聚合:
select time
from readings
when sensor_id in (1, 2)
group by time
having count(*) = 2
这会为您提供两个传感器都有数据的所有 time
。
从问题的其余部分来看,我认为您想在不与现有记录冲突的情况下更改记录上的传感器 ID(例如,从 1
到 2
)。这表明:
update readings r
set sensor_id = 2
where sensor_id = 1 and not exists (
select 1 from readings r1 where r1.sensor_id = 2 and r1.time = r.time
)