【问题标题】:How to find duplicate records and update using postgresql?如何使用 postgresql 查找重复记录和更新?
【发布时间】:2021-05-17 21:50:43
【问题描述】:
id userid deviceid isactive last_modified (timestamp)
1 12 fdghfgh true 2021-02-12
2 12 sdsdfg true 2021-02-14
3 5 fghfgh true 2021-01-12
4 15 dffdg true 2021-02-14
5 15 dofghfjdog true 2021-01-09

一个用户只能使用一台设备。上表用户 12 和 15 拥有两个活动设备。

如何在postgresql查询中将最近修改的设备设置为active,其他设备设置为false(对应用户)?

结果应该是:

id userid deviceid isactive last_modified (timestamp)
1 12 fdghfgh false 2021-02-12
2 12 sdsdfg true 2021-02-14
3 5 fghfgh true 2021-01-12
4 15 dffdg true 2021-02-14
5 15 dofghfjdog false 2021-01-09

【问题讨论】:

标签: sql postgresql duplicates sql-update


【解决方案1】:

您可以使用如下所示的 RANK () OVER 函数

这将根据每个用户 ID 组的最后修改日期为您提供每个条目的排名。

然后您可以编写更新查询以将 isactive 更新为 false where device_rank ! =1

select id,userid,deviceid,isactive,last_modified,
RANK () OVER ( 
        PARTITION BY userid
        ORDER BY last_modified DESC
    ) device_rank 
from deviceTable

【讨论】:

    【解决方案2】:

    如果您想设置这些值,请使用update。子查询用于计算应被视为活动的日期:

    update t
        set is_active = (last_modified = max_lst_modified)
        from (select user_id, max(last_modified) as max_last_modified
              from t
              group by user_id
             ) tt
        where tt.user_id = t.user_id;
    

    【讨论】:

      【解决方案3】:

      查询 1:(按 last_modified_time 对设备进行排名)

      select id,userid,deviceid,isactive,last_modified_timestamp,
      RANK () OVER ( 
              PARTITION BY user_id
              ORDER BY last_modified_timestamp DESC
          ) device_rank 
      from myschema.mytable rankTable 
      

      查询 2:(更新设备表以使只有一个活动设备 - 最近的设备)

      UPDATE myschema.mytable ud
      SET is_active = false
      FROM (select id,userid,deviceid,isactive,last_modified_timestamp,
      RANK () OVER ( 
              PARTITION BY user_id
              ORDER BY last_modified_timestamp DESC
          ) device_rank 
      from myschema.mytable) as rankTable
      WHERE ud.id=rankTable.id and rankTable.device_rank != 1;
      

      【讨论】:

        猜你喜欢
        • 2015-03-25
        • 1970-01-01
        • 2015-02-14
        • 1970-01-01
        • 2016-08-15
        • 2019-09-24
        • 2017-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多