Roy*_*mir 1 sql-server sql-order-by
我在网站上搜索过.这个问题有很多版本的答案.但找不到我要找的具体问题:
让我们说xxx,yyy,zzz有1列,3行:
1
2
3
SELECT a FROM xxx order by a asc
UNION
SELECT f FROM yyy order by f desc
UNION
SELECT t FROM zzz order by t asc
Run Code Online (Sandbox Code Playgroud)
所以期望的结果集是:
1
2
3
3
2
1
1
2
3
Run Code Online (Sandbox Code Playgroud)
UNION附近的语法错误.
我知道union的顺序问题(并且只有在需要整体ORDER BY时才知道如何解决它.)
题 :
我怎样才能得到我想要的输出?
您必须将单个 order by子句应用于整个 union,否则排序没有明确定义:
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
Run Code Online (Sandbox Code Playgroud)
然而,-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
Run Code Online (Sandbox Code Playgroud)
我不清楚为什么你认为它没有回答你的问题 - 可能是因为结果集中的其他列?如果是这样,您可以安排整个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
Run Code Online (Sandbox Code Playgroud)
结果:
a
----
1
2
3
3
2
1
1
2
3
Run Code Online (Sandbox Code Playgroud)