根据排名查找每个 ID 的值
Find Values for each ID based on rank
对于每个 ID,我想获得排名最低和第二低的值(可能的排名:1 - 7)。如果一个 ID 有两次相同的排名,我想 select 最新的,基于列 LastUpdate:
ID
value
rank
LastUpdate
1
a
1
2021-01-19
1
b
2
2021-01-19
1
c
3
2021-01-19
2
d
3
2021-01-19
2
e
3
2021-01-18
2
f
4
2021-01-18
3
g
2
2021-01-19
3
h
7
2021-01-19
3
i
7
2021-01-20
在这种情况下,我想要的输出是:
ID
value_lowest_rank
value_second_lowest_rank
1
a
b
2
d
e
3
g
i
使用row_number
按排名和日期对行进行编号,然后应用条件聚合:
with cte as (
select *, row_number() over (partition by id order by rank, lastupdate desc) as rn
from t
)
select id, max(case when rn = 1 then value end), max(case when rn = 2 then value end)
from cte
group by id
对于每个 ID,我想获得排名最低和第二低的值(可能的排名:1 - 7)。如果一个 ID 有两次相同的排名,我想 select 最新的,基于列 LastUpdate:
ID | value | rank | LastUpdate |
---|---|---|---|
1 | a | 1 | 2021-01-19 |
1 | b | 2 | 2021-01-19 |
1 | c | 3 | 2021-01-19 |
2 | d | 3 | 2021-01-19 |
2 | e | 3 | 2021-01-18 |
2 | f | 4 | 2021-01-18 |
3 | g | 2 | 2021-01-19 |
3 | h | 7 | 2021-01-19 |
3 | i | 7 | 2021-01-20 |
在这种情况下,我想要的输出是:
ID | value_lowest_rank | value_second_lowest_rank |
---|---|---|
1 | a | b |
2 | d | e |
3 | g | i |
使用row_number
按排名和日期对行进行编号,然后应用条件聚合:
with cte as (
select *, row_number() over (partition by id order by rank, lastupdate desc) as rn
from t
)
select id, max(case when rn = 1 then value end), max(case when rn = 2 then value end)
from cte
group by id