2015-01-07 42 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

相關問題