【问题标题】:SQL - Delete duplicates based on timestampSQL - 根据时间戳删除重复项
【发布时间】:2020-11-03 16:36:41
【问题描述】:

我的问题是有一个历史表,它每天都会提取一个表并给它一个时间戳。不幸的是,过去每天都会多次加载数据,这是不应该的。

就像:

  • 时间戳/id
  • 13.07.2020 15:01.../123
  • 13.07.2020 15:02.../123
  • 13.07.2020 15:03.../123
  • 14.07.2020 15:01.../123
  • 14.07.2020 15:02.../123
  • 14.07.2020 15:03.../123

应该是这样的:

  • 13.07.2020 15:01.../123
  • 14.07.2020 15:01.../123

我正在寻找一种方法来根据每天的第一个时间戳删除重复项。

您有什么想法以这种方式删除重复项吗?

提前谢谢你!

【问题讨论】:

    标签: sql sql-server tsql timestamp


    【解决方案1】:

    如果您只有两列,请使用聚合:

    select id, cmin(timestamp) as timestamp
    from t
    group by id, convert(date, timestamp);
    

    如果您有很多列并且想要完整的行,那么row_number() 可能是最好的选择:

    select t.*
    from (select t.*,
                 row_number() over (partition by id, convert(date, timestamp) order by timestamp) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    【讨论】:

    • 谢谢,示例中的列更多。我想删除除 min 之外的所有时间戳
    • @Bryan。 . .这就是为什么我提供了两个查询。我怀疑那是你真正想要的。
    【解决方案2】:

    我建议使用 CTE 删除:

    WITH cte AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY id, CONVERT(date, ts_col) ORDER BY ts_col) rn
        FROM yourTable
    )
    
    DELETE
    FROM cte
    WHERE rn > 1;     -- targets all records per day except for the first one
    

    【讨论】:

    • 谢谢!不幸的是,这个查询不考虑 id。仅删除每个 id 和每天的大于 1 的 RowNumber。
    • @Bryan 然后考虑更新后的答案,每个日期和 ID 分区。
    【解决方案3】:

    你可以使用这个选择来控制:

    select  a.* from yourtable a
    inner join
    (
        select id,convert(date,[datetime]) [date], MIN([datetime]) [datetime]
        from yourtable
        group by id,convert(date,[datetime])
    ) b on a.id = b.id and convert(date,a.[datetime]) = b.[date] and a.[datetime] <> b.[datetime]
    

    还有删除:

    delete  a from yourtable a
    inner join
    (
        select id,convert(date,[datetime]) [date], MIN([datetime]) [datetime]
        from yourtable
        group by id,convert(date,[datetime])
    ) b on a.id = b.id and convert(date,a.[datetime]) = b.[date] and a.[datetime] <> b.[datetime]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多