【问题标题】:How to delete sequential duplicate rows with unique identifier?如何删除具有唯一标识符的连续重复行?
【发布时间】:2020-04-30 17:12:18
【问题描述】:

我有下表,用于收集我感兴趣的产品的信息。

CREATE TABLE priceinfo (
    date TEXT,
    title TEXT,
    sku INTEGER,
    price REAL,
    media TEXT,
    url TEXT
);

如何从数据库中删除具有不同日期的多行重复数据的条目?样本是下面的数据。我想保留条目,因为它们会发生变化,而不是日复一日的条目。

1 2019-12-10    Product1    123456789   25.99   Blu-ray https://www.example.com
2 2019-12-11    Product1    123456789   21.59   Blu-ray https://www.example.com
3 2019-12-12    Product1    123456789   21.59   Blu-ray https://www.example.com
4 2019-12-13    Product1    123456789   21.59   Blu-ray https://www.example.com
5 2019-12-14    Product1    123456789   20.89   Blu-ray https://www.example.com
6 2019-12-15    Product1    123456789   21.59   Blu-ray https://www.example.com

在示例中,我希望保留第 #1、#2、#5 和 #6 行,但要删除 #3 和 #4,因为除了这两行中的日期之外没有任何信息发生变化。

【问题讨论】:

    标签: sql sqlite duplicates


    【解决方案1】:

    假设日期没有重复,您可以使用lag()

    select t.*
    from (select t.*,
                 lag(date) over (order by date) as prev_date,
                 lag(date) over (partition by title, sku, price, media, url order by date) as prev_date2
          from t
         ) t
    where prev_date is null or prev_date <> prev_date2;
    

    编辑:

    假设日期是唯一的,您可以使用以下逻辑:

    with todelete as (
          select t.*
          from (select t.*,
                       lag(date) over (order by date) as prev_date,
                       lag(date) over (partition by title, sku, price, media, url order by date) as prev_date2
                from t
               ) t
          where prev_date is null or prev_date <> prev_date2
         )
    delete from t
        where t.date in (select cte.date from cte);
    

    【讨论】:

    • 假设在我的示例中,我有产品 #1、产品 #2 等。您的 SQL 会仅影响特定产品还是会影响具有相同日期的所有产品?
    • 您只需更改 prev_date 为 null 或 prev_date prev_date2;其中 prev_date2 为空;戈登的回答将作为你的榜样
    • 我将如何将其包装在 DELETE 语句中?我似乎找不到任何具有如此复杂 SQL 的删除示例,因此 DELETE FROM priceinfo WHERE EXISTS (&lt;query above&gt;); 或类似示例不起作用。
    • @ktBonefish 。 . .如果您想要每个产品,那么您希望按该列进行分区。
    • 我看到@GordonLinoff。谢谢
    猜你喜欢
    • 2015-01-02
    • 2018-09-29
    • 2020-05-24
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多