【问题标题】:PostgreSQL select rows with specific columns identicalPostgreSQL选择特定列相同的行
【发布时间】:2015-03-05 03:47:02
【问题描述】:

我需要删除仅在特定列中具有相同值的行。例如,在下面的摘录中,我想选择除最后一行之外的所有行,它等于 CODE、START_DATE 和 TYPE 列的倒数第二行(这意味着忽略 END_DATE 列的值)。

  code         | start_date     | end_date     | type
---------------+----------------+--------------+------
C086000-T10001 | 2014-11-11     | 2014-11-12   | 01
C086000-T10001 | 2014-11-11     | 2014-11-11   | 03
C086000-T10002 | 2014-12-03     | 2014-12-10   | 03
C086000-T10002 | 2014-01-03     | 2014-01-04   | 03
C086000-T10003 | 2012-02-27     | 2014-02-28   | 03
C086000-T10003 | 2014-08-11     | 2014-11-12   | 01
C086000-T10003 | 2014-08-11     | 2014-08-20   | 01

我该怎么做?

编辑:以下查询返回too much columns for a subquery错误消息:

SELECT * FROM my_table WHERE code NOT IN (SELECT DISTINCT code, start_date, type FROM my_table) ;

非常感谢您的帮助!

【问题讨论】:

  • 不,抱歉(由于我的样本复制粘贴而导致的错误已修复)。

标签: postgresql duplicates greatest-n-per-group


【解决方案1】:

这可以使用 Postgres 的 distinct on 运算符来完成:

select distinct on (code, start_date, type) code, start_date, end_date, type
from the_table
order by code, start_date, type;

如果您更喜欢使用标准 SQL,也可以使用窗口函数来完成:

select code, start_date, end_date, type
from (
    select code, start_date, end_date, type, 
           row_number() over (partition by code, start_date, type order by end_date) as rn
    from the_table
) t
where rn = 1
order by code, start_date, type;

SQLFiddle 示例:http://sqlfiddle.com/#!15/c5044/1

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2016-10-02
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2020-05-08
    • 2018-12-06
    • 2022-12-03
    • 2016-12-25
    相关资源
    最近更新 更多