根据 2 列 Oracle 对结果进行排序
Sorting the result based on 2 columns Oracle
我有两列日期和数字,日期中的值为空值。我可以用日期和数字列一起排序检查日期是否为空然后用数字排序吗?
dt num
3/20/2022 1
3/16/2022 3
3/17/2022 4
3/18/2022 5
NULL 6
NULL 7
3/19/2022 8
*Expected Output*
dt num
3/16/2022 3
3/17/2022 4
3/18/2022 5
NULL 6
NULL 7
3/19/2022 8
3/20/2022 1
如果有日期,我们需要按日期排序,如果没有,我们搜索日期不为空的前一行。
这确实意味着我们每行 运行 一个 sub-query,因此对于大型查询来说会很慢。
create table d(
dt date,
num int);
insert into d (dt, num)
select to_date('2022-03-20','YYYY-MM-DD'),1 from dual union all
select to_date('2022-03-16','YYYY-MM-DD'),3 from dual union all
select to_date ('2022-03-17','YYYY-MM-DD'), 4 from dual union all
select to_date('2022-03-17','YYYY-MM-DD'),5 from dual union all
select to_date('2022-03-18','YYYY-MM-DD'),6 from dual union all
select to_date('2022-03-16','YYYY-MM-DD'),10 from dual union all
select to_date('2022-03-19','YYYY-MM-DD'),9 from dual;
insert into d ( num)
select 7 from dual union all
select 8 from dual ;
select
dt,
num,
( select dt
from d
where num <= d1.num and dt is not null
order by num desc
fetch next 1 rows only
) as dt_plus
from d d1
order by dt_plus,num;
DT | NUM | DT_PLUS
:-------- | --: | :--------
16-MAR-22 | 3 | 16-MAR-22
16-MAR-22 | 10 | 16-MAR-22
17-MAR-22 | 4 | 17-MAR-22
17-MAR-22 | 5 | 17-MAR-22
18-MAR-22 | 6 | 18-MAR-22
null | 7 | 18-MAR-22
null | 8 | 18-MAR-22
19-MAR-22 | 9 | 19-MAR-22
20-MAR-22 | 1 | 20-MAR-22
db<>fiddle here
我有两列日期和数字,日期中的值为空值。我可以用日期和数字列一起排序检查日期是否为空然后用数字排序吗?
dt num
3/20/2022 1
3/16/2022 3
3/17/2022 4
3/18/2022 5
NULL 6
NULL 7
3/19/2022 8
*Expected Output*
dt num
3/16/2022 3
3/17/2022 4
3/18/2022 5
NULL 6
NULL 7
3/19/2022 8
3/20/2022 1
如果有日期,我们需要按日期排序,如果没有,我们搜索日期不为空的前一行。
这确实意味着我们每行 运行 一个 sub-query,因此对于大型查询来说会很慢。
create table d( dt date, num int);
insert into d (dt, num) select to_date('2022-03-20','YYYY-MM-DD'),1 from dual union all select to_date('2022-03-16','YYYY-MM-DD'),3 from dual union all select to_date ('2022-03-17','YYYY-MM-DD'), 4 from dual union all select to_date('2022-03-17','YYYY-MM-DD'),5 from dual union all select to_date('2022-03-18','YYYY-MM-DD'),6 from dual union all select to_date('2022-03-16','YYYY-MM-DD'),10 from dual union all select to_date('2022-03-19','YYYY-MM-DD'),9 from dual;
insert into d ( num) select 7 from dual union all select 8 from dual ;
select dt, num, ( select dt from d where num <= d1.num and dt is not null order by num desc fetch next 1 rows only ) as dt_plus from d d1 order by dt_plus,num;
DT | NUM | DT_PLUS :-------- | --: | :-------- 16-MAR-22 | 3 | 16-MAR-22 16-MAR-22 | 10 | 16-MAR-22 17-MAR-22 | 4 | 17-MAR-22 17-MAR-22 | 5 | 17-MAR-22 18-MAR-22 | 6 | 18-MAR-22 null | 7 | 18-MAR-22 null | 8 | 18-MAR-22 19-MAR-22 | 9 | 19-MAR-22 20-MAR-22 | 1 | 20-MAR-22
db<>fiddle here