PL/SQL 在 a = b 处排序
PL/SQL ORDER BY WHERE a = b
我有一个 table 看起来像这样
ID NUMBER,
NAME VARCHAR(2),
Sub_ID
Sub_ID如果不是可以为空,它包含ID字段中的一个数字。
数据可能如下所示。
ID NAME SUB_ID
1 A
2 B 1
3 C 1
4 D 3
5 E 2
6 F 1
7 G 6
我希望它像这样排序
ID NAME SUB_ID
1 A
2 B 1
5 E 2
3 C 1
4 D 3
6 F 1
7 G 6
我试过这样排序
ORDER BY ID ASC, Sub_ID ASC
但这没有用,这就是为什么我正在寻找一种方法来对这样的东西进行排序。
ORDER BY WHERE(ID ASC=Sub_ID) ASC
听起来像 connect by
和 order siblings by
可能就是您想要的:
with your_table as (select 1 id, 'A' name, null sub_id from dual union all
select 2 id, 'B' name, 1 sub_id from dual union all
select 3 id, 'C' name, 1 sub_id from dual union all
select 4 id, 'D' name, 3 sub_id from dual union all
select 5 id, 'E' name, 2 sub_id from dual union all
select 6 id, 'F' name, 1 sub_id from dual union all
select 7 id, 'G' name, 6 sub_id from dual)
select *
from your_table
connect by prior id = sub_id
start with sub_id is null
order siblings by sub_id;
ID NAME SUB_ID
---------- ---- ----------
1 A
2 B 1
5 E 2
3 C 1
4 D 3
6 F 1
7 G 6
我有一个 table 看起来像这样
ID NUMBER,
NAME VARCHAR(2),
Sub_ID
Sub_ID如果不是可以为空,它包含ID字段中的一个数字。 数据可能如下所示。
ID NAME SUB_ID
1 A
2 B 1
3 C 1
4 D 3
5 E 2
6 F 1
7 G 6
我希望它像这样排序
ID NAME SUB_ID
1 A
2 B 1
5 E 2
3 C 1
4 D 3
6 F 1
7 G 6
我试过这样排序
ORDER BY ID ASC, Sub_ID ASC
但这没有用,这就是为什么我正在寻找一种方法来对这样的东西进行排序。
ORDER BY WHERE(ID ASC=Sub_ID) ASC
听起来像 connect by
和 order siblings by
可能就是您想要的:
with your_table as (select 1 id, 'A' name, null sub_id from dual union all
select 2 id, 'B' name, 1 sub_id from dual union all
select 3 id, 'C' name, 1 sub_id from dual union all
select 4 id, 'D' name, 3 sub_id from dual union all
select 5 id, 'E' name, 2 sub_id from dual union all
select 6 id, 'F' name, 1 sub_id from dual union all
select 7 id, 'G' name, 6 sub_id from dual)
select *
from your_table
connect by prior id = sub_id
start with sub_id is null
order siblings by sub_id;
ID NAME SUB_ID
---------- ---- ----------
1 A
2 B 1
5 E 2
3 C 1
4 D 3
6 F 1
7 G 6