5

In SQL Server 2008, we can use Union/Unino All to put two results together, but I want to add order by for the final result. How can do that?

What I want is something like:

select id1 as id, * from ...
Union All
select id2 as id, * from ...
order by id

Help please. Thanks.

Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
KentZhou
  • 24,805
  • 41
  • 134
  • 200

5 Answers5

12

As noted in the comments, the pseudocode you've given should work, applying the order by to the combined result set. If you're trying to order in such a way that the two result sets are kept distinct, you'd need to introduce an artificial sort column, such as:

select id1 as id, *, 1 as MySortKey from ...
Union All
select id2 as id, *, 2 as MySortKey from ...
order by MySortKey, id
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
1

You can use this query as well

select * from (
select id1 as id, * from ...
Union All
select id2 as id, * from ...
) aaaa
order by id
NoNaMe
  • 6,020
  • 30
  • 82
  • 110
0

All of these answers included the original poster's attempt is just plain confusing or overly complicated. A simple and easy to follow explanation is here:

How to order by with union

with,

"Just write

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name

the order by is applied to the complete resultset " Just use UNION ALL instead of UNION here.

Community
  • 1
  • 1
eaglei22
  • 2,589
  • 1
  • 38
  • 53
0

use this code:

Select * from 
(select id1 as id, * from ...
Union All
select id2 ad id,  * from ...
order by id) as t
order by t.id
ABI
  • 1,714
  • 15
  • 14
  • I don't see how the outer query would change the results returned by the inner in any way. – Joe Stefanelli Dec 17 '10 at 14:43
  • @Joe: Perhaps if the first set isn't ordered? The outer order by could be useful if you're EXEC'ing sprocs that you're unsure of the returned order. – JasonCoder Dec 17 '10 at 14:49
  • @JasonCoder: The syntax can be confusing, but the order by in the inner query (which is the OP's original query) is actually applied to the combined result of the two select statements, not just to the second statement. – Joe Stefanelli Dec 17 '10 at 14:52
0

use northwind

select OrderID, ProductID from [Order Details] a
UNION all
Select OrderID, EmployeeID from Orders b
order by a.ProductID
CoolBeans
  • 20,654
  • 10
  • 86
  • 101