问题
I've searched here on the site. and there are many version of answers to this question. But couldn't find what I was looking for for this specific question :
lets say that xxx,yyy,zzz has 1 column, 3 rows:
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
So the desired result set is:
1
2
3
3
2
1
1
2
3
There is an error of incorrect syntax near UNION.
I'm aware of the order problem with union (and know how to solve it only if an overall ORDER BY is required.)
Question :
how can I get my desired output?
回答1:
You have to apply a single order by clause to the entire union, or else the ordering isn't well defined:
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
However, the -f might feel like a dirty trick to achieve the opposite ordering (or may not be entirely what you want if NULLs are included), so you could also do:
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
I'm unclear on why you don't think it answers your question - perhaps because of the additional columns in the result set? If so, you can arrange for the whole UNION to be in a subquery:
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
results:
a
----
1
2
3
3
2
1
1
2
3
回答2:
Things to keep in mind while UNIONing:
UNIONallows you to create aRESULTSETwith same type data from differentSELECTstatement.- The
RESULTSETis generated with the column name of leading(first)SELECTstatement. - For other
SELECTstatement columns data type should be matched according to the leading(first)SELECTstatement. - For
ORDERing, its applied on theRESULTSET, consequently in case ofUNION, it only allowsORDER BYat the lastSELECTstatement but takes column name according to leading(first)SELECTstatement, so below example is true: - Finally, since in the
RESULTSETforUNIONingwith different tables/sources aggregates all data into a column(according to first(leading)SELECTstatement), so you can not applyASCandDESCfor same column.
Right
SELECT a FROM xxx
UNION
SELECT f FROM yyy
UNION
SELECT t FROM zzz order by a asc
Wrong: according to you
SELECT a FROM xxx
UNION
SELECT f FROM yyy
UNION
SELECT t FROM zzz order by a asc, a desc
来源:https://stackoverflow.com/questions/8457103/sql-server-query-with-union-and-different-order-by-to-each-section