2015-01-07 44 views
0

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

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 

我该怎么做?

编辑:下面的查询返回一个太多列的子查询错误消息:

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

许多感谢您的帮助!

+0

不,对不起(由于我的示例的复制粘贴,错误已修复)。 – wiltomap

回答

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

+0

就是这样,非常感谢! – wiltomap

相关问题