簡體   English   中英

聯合所有:按合並排序(無子查詢)

[英]Union all: Order by coalesce (without subquery)

我有兩個要合並的表:WORKORDER_1 和 WORKORDER_2。

--fake tables in WITH clause

with workorders_1 as (
select 'WO1' as wonum,      null as parent from dual
union all
select 'WO100' as wonum, 'WO1' as parent from dual
union all
select 'WO100' as wonum, 'WO1' as parent from dual
),

workorders_2 as (
select 'WO200' as wonum, 'WO2' as parent from dual
union all
select 'WO200' as wonum, 'WO2' as parent from dual
union all
select 'WO2' as wonum, null as parent from dual
)

select * from workorders_1
union all
select * from workorders_2

WONUM    PARENT
-----    ------
WO1         
WO100    WO1   
WO100    WO1   
WO200    WO2   
WO200    WO2   
WO2  

我想通過合並的父 ID 對聯合表進行排序:

  • 如果 PARENT 不為空,則使用它
  • 否則,使用 WONUM

結果如下所示:

WONUM    PARENT    [order by/coalesce]
-----    ------    ----------
WO1                [WO1]
WO100    WO1       [WO1]
WO100    WO1       [WO1]

WO2                [WO2]
WO200    WO2       [WO2]
WO200    WO2       [WO2]

我更願意在不將查詢包裝為子查詢的情況下進行排序。

  • 雖然這個問題中的示例查詢很簡單,但我真正的查詢已經很長了,添加子查詢會使其更難閱讀。

有沒有一種使用類似合並邏輯的方式排序——而不使用子查詢?

您可以在order by子句中使用coalesce() 對於此類表達式,Oracle 要求您將union查詢包裝在子查詢中:

select *
from (
    select * from workorders_1
    union all
    select * from workorders_2
) t
order by coalesce(parent, wonum), wonum

DB Fiddle 上的演示

您的列名稱表明正在進行層次結構。 如果是這種情況,那么您應該考慮查詢數據的分層方式https://docs.oracle.com/database/121/SQLRF/queries003.htm#SQLRF52332

您可以在每個 union alls 中使用 connect by query。 如果您從看起來是父行的內容開始,默認排序將為您提供所需的內容:

with workorders_1 as (
select 'WO1' as wonum,      null as parent from dual
union all
select 'WO100' as wonum, 'WO1' as parent from dual
union all
select 'WO100' as wonum, 'WO1' as parent from dual
),
workorders_2 as (
select 'WO200' as wonum, 'WO2' as parent from dual
union all
select 'WO200' as wonum, 'WO2' as parent from dual
union all
select 'WO2' as wonum, null as parent from dual
)
select wonum, parent from workorders_1
connect by parent  = prior wonum
start with parent is null
union all
select wonum, parent from workorders_2
connect by parent  = prior wonum
start with parent is null

WONUM   PARENT
WO1   
WO100   WO1
WO100   WO1
WO2  
WO200   WO2
WO200   WO2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM