为每列1选择列2的最大值

8ljdwjyq  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(406)

给出下表

+----+-----------+-----------+
| id | date      | person_id |
+----+-----------+-----------+
| 1  |19/06/2019 | 1         |
| 2  |18/07/2010 | 2         |
| 3  |19/06/2020 | 1         |
| 4  |17/06/2020 | 2         |
| 5  |28/06/2020 | 3         |
+----+-----------+-----------+

我想要这个输出

+----+-----------+-----------+
| id | date      | person_id |
+----+-----------+-----------+
| 3  |19/06/2020 | 1         |
| 4  |17/06/2020 | 2         |
| 5  |28/06/2020 | 3         |
+----+-----------+-----------+

换言之,我想返回每人的最长日期。我试过这样的方法

SELECT DISTINCT pp.date, pp.id FROM P_PROV pp
            WHERE (SELECT MAX(aa.date) 
            FROM P_PROV aa) = pp.date;

这个只返回一行(当然,因为max只返回最长日期),但是我真的不知道如何处理这个问题,任何帮助都将不胜感激

62lalag4

62lalag41#

ROW_NUMBER 提供了一种处理此问题的方法:

SELECT id, date, person_id
FROM
(
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY date DESC) rn
    FROM yourTable t
) t
WHERE rn = 1;
mftmpeh8

mftmpeh82#

oracle使用聚合有一种有趣的方法:

select max(id) keep (dense_rank first order by date desc) as id,
       max(date) as date, person_id
from P_PROV
group by person_id;

考虑到您的ID正在增加,这可能也会满足您的要求:

select max(id) as id, max(date) as date, person_id
from P_PROV
group by person_id;

相关问题