【问题标题】:SELECT query for skipping rows with duplicates but leaving the first and the last occurrences in PostgreSQL用于跳过重复行但在 PostgreSQL 中保留第一次和最后一次出现的 SELECT 查询
【发布时间】:2018-11-09 08:27:17
【问题描述】:

我有一个包含项目、日期和价格的表,我正在尝试找到一种在 PostgreSQL 中编写 SELECT 查询的方法,该查询将跳过具有重复价格的行,这样,只有第一次和最后一次出现相同的价格一行会留下来。价格变化后,它可以恢复到以前的值,它也应该被保留。

id   date        price   item
1    20.10.2018  10      a
2    21.10.2018  10      a
3    22.10.2018  10      a
4    23.10.2018  15      a
5    24.10.2018  15      a
6    25.10.2018  15      a
7    26.10.2018  10      a
8    27.10.2018  10      a
9    28.10.2018  10      a
10   29.10.2018  10      a
11   26.10.2018  3       b
12   27.10.2018  3       b
13   28.10.2018  3       b
14   29.10.2018  3       c

结果:

id   date        price   item
1    20.10.2018  10      a
3    22.10.2018  10      a
4    23.10.2018  15      a
6    25.10.2018  15      a
7    26.10.2018  10      a
10   29.10.2018  10      a
11   26.10.2018  3       b
13   28.10.2018  3       b
14   29.10.2018  3       c

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您可以使用lag()lead()

    select id, date, price, item
    from (select t.*,
                 lag(price) over (partition by item order by date) as prev_price,
                 lead(price) over (partition by item order by date) as next_price
          from t
         ) t
    where prev_price is null or prev_price <> price or
          next_price is null or next_price <> price
    

    【讨论】:

    • 非常感谢!有没有什么简单的方法可以修改这个 SQL 查询,这样这次只有第一次出现相同价格的行会保留?
    • @GeorgeP。 . . .你可以选择你想要的列。
    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2016-05-10
    • 2023-03-04
    • 2022-11-19
    • 1970-01-01
    相关资源
    最近更新 更多