简体   繁体   中英

Using DB2, how do you select rows with MAX for one column and then select rows with MAX on the resulting subset for another column on the same table?

For example this is the data set on the table PEOPLE:

Name     Due_Date     Seq_Num
Peter    2020-03-01   001
Peter    2020-03-01   002
Peter    2020-03-02   001
Paul     2020-03-03   001
Paul     2020-03-03   002
Paul     2020-03-04   001
Paul     2020-03-04   002
Mary     2020-03-05   001
Mary     2020-03-05   002

If I do SELECT NAME, MAX(DUE_DATE), MAX(SEQ_NUM) FROM PEOPLE GROUP BY NAME it will return the ff:

Name     Due_Date     Seq_Num
Peter    2020-03-02   002
Paul     2020-03-04   002
Mary     2020-03-05   002

But what I want is:

Name     Due_Date     Seq_Num
Peter    2020-03-02   001
Paul     2020-03-04   002
Mary     2020-03-05   002

Because I want the MAX() Seq_Num for the MAX() Due_Date and for Peter, on his MAX() Due_Date, there is no Seq_Num 002, so the value output should be 001. How do I select this via SQL (DB2)?

Try this:

/*
WITH PEOPLE (Name, Due_Date, Seq_Num) AS 
(
VALUES
  ('Peter', '2020-03-01', '001')
, ('Peter', '2020-03-01', '002')
, ('Peter', '2020-03-02', '001')
, ('Paul ', '2020-03-03', '001')
, ('Paul ', '2020-03-03', '002')
, ('Paul ', '2020-03-04', '001')
, ('Paul ', '2020-03-04', '002')
, ('Mary ', '2020-03-05', '001')
, ('Mary ', '2020-03-05', '002')
)
*/
SELECT Name, Due_Date, Seq_Num 
FROM
(
SELECT Name, Due_Date, Seq_Num, RANK() OVER (PARTITION BY NAME ORDER BY Due_Date DESC, Seq_Num DESC) MX_
FROM PEOPLE
)
WHERE MX_ = 1;

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