[英]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:例如,这是表 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:如果我执行 SELECT NAME, MAX(DUE_DATE), MAX(SEQ_NUM) FROM PEOPLE GROUP BY NAME,它将返回 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)?因为我想要 MAX() Due_Date 和 Peter 的 MAX() Seq_Num,在他的 MAX() Due_Date 上,没有 Seq_Num 002,所以值输出应该是 001。我如何通过 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.