简体   繁体   中英

Select a distinct ID with the maximum date

I see some questions relating to mine, but they are not exactly the same.

I need to make a SELECT in a DB2 database where I keep only distinct IDs with their data.

Example, I have some datas :

ID    DATE_BEGIN   DATE_END
1111  2014-01-01   2016-01-02
1111  2018-01-05   2018-01-03
1111  1990-01-01   9999-12-31
2222  1998-02-02   2000-12-20

In my case, I want to keep :

1111  1990-01-01   9999-12-31
2222  1998-02-02   2000-12-20

My SELECT statement:

SELECT
ID, DATE_BEGIN, DATE_END
FROM TABLE_NAME T1
WHERE DATE_END = (SELECT
                  MAX(DATE_END)
                  FROM TABLE_NAME T2
                  WHERE T2.DATE_END = T1.DATE_END)

But I keep getting every records.

Thanks for the help !

I asked a similar question previously, please refer to my post here: Get the latest date for each record

SELECT ID, DATE_BEGIN, DATE_END
FROM (
SELECT ID, DATE_BEGIN, DATE_END
      ,ROW_NUMBER() OVER (PARTITION BY [ID] ORDER BY [DATE_END] DESC) RN 
FROM TABLE_NAME
)A
WHERE A.RN = 1

Credit goes to the original answer in my post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM