Select 对多列排序后每个 ID 的值
Select value for each id after sorting on multiple columns
寻找一种方法 select 每个 "id1" 一个 "status" 基于最低 "id2" 然后最大 "the_date"。我能够通过创建多个子查询来做到这一点,首先找到每个 id1 的最小 id2,然后找到每个 id2 的最大值 "the_date" 并将它们连接回原始 table。但似乎应该有一种方法可以用一个 qry 来做到这一点?
with data as(
Select 101 as id1, 11 as id2, to_date('01/02/2019','MM/DD/YYYY') as the_date, 'a' as status from dual union all
Select 101 as id1, 11 as id2, to_date('01/01/2019','MM/DD/YYYY') as the_date, 'b' as status from dual union all
Select 101 as id1, 24 as id2, to_date('01/02/2019','MM/DD/YYYY') as the_date, 'g' as status from dual union all
Select 200 as id1, 41 as id2, to_date('01/02/2017','MM/DD/YYYY') as the_date, 'c' as status from dual union all
Select 200 as id1, 61 as id2, to_date('01/02/2019','MM/DD/YYYY') as the_date, 'z' as status from dual)
查询的结果应该是:
id1|id2|the_date|status
101|11|'01/02/2019'|a
200|41|'01/02/2017'|c
您可以使用 row_number()
:
select d.*
from (select d.*,
row_number() over (partition by id1 order by id2, the_date desc) as seqnum
from data d
) d
where seqnum = 1;
Here 是一个 db<>fiddle.
寻找一种方法 select 每个 "id1" 一个 "status" 基于最低 "id2" 然后最大 "the_date"。我能够通过创建多个子查询来做到这一点,首先找到每个 id1 的最小 id2,然后找到每个 id2 的最大值 "the_date" 并将它们连接回原始 table。但似乎应该有一种方法可以用一个 qry 来做到这一点?
with data as(
Select 101 as id1, 11 as id2, to_date('01/02/2019','MM/DD/YYYY') as the_date, 'a' as status from dual union all
Select 101 as id1, 11 as id2, to_date('01/01/2019','MM/DD/YYYY') as the_date, 'b' as status from dual union all
Select 101 as id1, 24 as id2, to_date('01/02/2019','MM/DD/YYYY') as the_date, 'g' as status from dual union all
Select 200 as id1, 41 as id2, to_date('01/02/2017','MM/DD/YYYY') as the_date, 'c' as status from dual union all
Select 200 as id1, 61 as id2, to_date('01/02/2019','MM/DD/YYYY') as the_date, 'z' as status from dual)
查询的结果应该是:
id1|id2|the_date|status
101|11|'01/02/2019'|a
200|41|'01/02/2017'|c
您可以使用 row_number()
:
select d.*
from (select d.*,
row_number() over (partition by id1 order by id2, the_date desc) as seqnum
from data d
) d
where seqnum = 1;
Here 是一个 db<>fiddle.