postgresql:更新表,确保行具有唯一的时间戳(没有重复的unix时间戳)

6ljaweal  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(305)

我有一个带有unix时间戳的gps跟踪表,如下所示:

SELECT * FROM mytable LIMIT 10;
    id     |    lat     |    lon     |  seconds   | speed 
-----------+------------+------------+------------+-------
 536889001 | 41.1794675 | -8.6017187 | 1460465697 |  1.25
 536889001 | 41.1794709 |  -8.601675 | 1460465698 |     2
 536889001 | 41.1794636 | -8.6016337 | 1460465700 |  1.25
 536889001 | 41.1794468 | -8.6016014 | 1460465700 |   2.5
 536889001 | 41.1794114 | -8.6015662 | 1460465701 |   3.5
 536889001 | 41.1794376 | -8.6015672 | 1460465703 |   1.5
 536889001 |   41.17944 | -8.6015516 | 1460465703 |   1.5
 536889001 | 41.1794315 | -8.6015353 | 1460465704 |   1.5
 536889001 | 41.1794367 | -8.6015156 | 1460465705 |  1.25
 536889001 | 41.1794337 | -8.6014974 | 1460465706 |  1.75
 (10 rows)

seconds 是unix时间戳。我想通过只选择一行来更新表,对于记录的时间戳超过1的行。例如,在上面的例子中,我们在时间戳处看到两行 1460465700 以及 1460465703 .

4dc9hkyq

4dc9hkyq1#

如果行中没有唯一的id,这是很棘手的。但假设值的组合是唯一的,则可以使用:

update gps
    set . . . 
    from (select gps.*, count(*) over (partition by id, seconds) as cnt,
                 row_number() over (partition by id, seconds order by seconds) as seqnum
          from gps
         ) gps2
     where gps2.cnt > 1 and pgs2.seqnum = 1 and
           gps2.seconds = pgs.seconds and
           gps2.id = gps.id and
           gps2.speed = gps.speed and
           gps2.lat = gps.lat and
           gps2.lon = gps.lon ;

我建议您向表中添加一个惟一的id,这样就简单多了(即使表中有重复的id,也可以保证工作)。

相关问题