你必須子句應用單爲了將整個工會,否則順序是不明確的:
SELECT a,1 as Pos,a as Ord from xxx
UNION ALL
SELECT f,2,-f from yyy
UNION ALL
SELECT t,3,t from zzz
ORDER BY Pos,Ord
然而,-f
可能會覺得像一個骯髒的把戲實現了相反順序(或可能不完全,你想要什麼,如果NULL
s的在內),所以你也可以這樣做:
SELECT a,1 as Pos,a as OrdAsc,0 as OrdDesc from xxx
UNION ALL
SELECT f,2,0,f from yyy
UNION ALL
SELECT t,3,t,0 from zzz
ORDER BY Pos asc,Ord asc,OrdDesc desc
我不明白爲什麼你不認爲它回答你的問題 - 也許是因爲結果集中的附加列?如果是這樣,你可以安排整個UNION
是在一個子查詢:
create table #xxx (a int not null)
create table #yyy (f int not null)
create table #zzz (t int not null)
insert into #xxx (a) select 1 union all select 2 union all select 3
insert into #yyy (f) select 1 union all select 2 union all select 3
insert into #zzz (t) select 1 union all select 2 union all select 3
SELECT a FROM (
SELECT a,1 as Pos,a as Ord from #xxx
UNION ALL
SELECT f,2,-f from #yyy
UNION ALL
SELECT t,3,t from #zzz
) t
ORDER BY Pos,Ord
結果:
a
----
1
2
3
3
2
1
1
2
3
可以顯示設定期望的結果的例子嗎? – Kenneth
@Kenneth我沒有... –
@RoyiNamir,你應該等待更多的答案,然後選擇最好的,謝謝你的時間。 –