oracle 如何获取不同组中每一行的最后一行[duplicate]

7ivaypg9  于 2022-11-28  发布在  Oracle
关注(0)|答案(3)|浏览(213)

This question already has answers here:

Fetch the rows which have the Max value for a column for each distinct value of another column (35 answers)
GROUP BY with MAX(DATE) [duplicate] (6 answers)
Select First Row of Every Group in sql [duplicate] (2 answers)
Oracle SQL query: Retrieve latest values per group based on time [duplicate] (2 answers)
Get value based on max of a different column grouped by another column [duplicate] (1 answer)
Closed 2 hours ago.
I have this table that shows the same id with different types and every type have the same rank that ordered by start date.
| id | type | start date | rank |
| ------------ | ------------ | ------------ | ------------ |
| 111 | 15 | 1/1/22 | 1 |
| 111 | 15 | 1/3/22 | 1 |
| 111 | 15 | 2/04/22 | 1 |
| 111 | 23 | 1/02/22 | 2 |
| 111 | 23 | 1/3/22 | 2 |
| 111 | 25 | 16/03/22 | 3 |
I want to get table that will show only the last row for every rank
| id | type | start date | rank |
| ------------ | ------------ | ------------ | ------------ |
| 111 | 15 | 2/04/22 | 1 |
| 111 | 23 | 1/3/22 | 2 |
| 111 | 25 | 16/03/22 | 3 |

vsmadaxz

vsmadaxz1#

使用group by并获取结果

select id,type,MAX(startdate) AS startdate,rank 
from TABLENAME
GROUP BY id,type,rank
6tdlim6h

6tdlim6h2#

您可以像这样使用ROW_NUMBER()

select *
from (
    select "id", "type", "start date", "rank", 
        row_number() over (partition by "type" order by "start date" desc) rnk
    from Table1 ) t
where t.rnk = 1

SQL小提琴
注意:您可以在partition by(如"start date", "rank")之后以及order by之后添加任意列组合

rta7y2nd

rta7y2nd3#

我们可以在子查询中使用FIRST_VALUEDISTINCT,并使用ROWNUM添加rank列:

SELECT "id", "type", startdate, ROWNUM AS rank
FROM
(SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") OVER 
(PARTITION BY "type" ORDER BY "start date" DESC) AS startdate
FROM Table1) groupedData;

请注意,如果date列可以是NULL,则此查询将失败(与其他答案中的查询一样)!为了避免这种情况,我们可以添加一个IGNORE NULLS子句:

SELECT "id", "type", startdate, ROWNUM AS rank
FROM
(SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") IGNORE NULLS OVER 
(PARTITION BY "type" ORDER BY "start date" DESC 
 ROWS BETWEEN unbounded preceding AND unbounded following) AS startdate
FROM Table1) groupedData;

我不知道您描述中的“ranking”列是否已经包含了正确的行号信息,是否可以安全地用于此目的,或者这是否不可能或风险太大。
如果可以使用它,就不需要子查询来获取行号。同样,有两个选项可以忽略或不忽略NULL值:

SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") OVER
(PARTITION BY "type" ORDER BY "start date" DESC ) AS startdate,
 "rank"
FROM Table1
ORDER BY "id", "type", "rank";

SELECT DISTINCT "id", "type",
FIRST_VALUE("start date") IGNORE NULLS OVER 
(PARTITION BY "type" ORDER BY "start date" DESC 
 ROWS BETWEEN unbounded preceding AND unbounded following) AS startdate,
 "rank"
FROM Table1
ORDER BY "id", "type", "rank";

相关问题