如何为Union结果添加订单?

时间:2010-12-17 14:13:38

标签: sql-server sql-server-2008

在SQL Server 2008中,我们可以使用Union / Unino All将两个结果放在一起,但我想为最终结果添加order by。怎么办?

我想要的是:

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

请帮助。谢谢。

5 个答案:

答案 0 :(得分:9)

如评论中所述,您提供的伪代码应该有效,将顺序应用于组合结果集。如果您尝试以两种结果集保持不同的方式进行排序,则需要引入人工排序列,例如:

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

答案 1 :(得分:1)

您也可以使用此查询

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

答案 2 :(得分:0)

使用此代码:

Select * from 
(select id1 as id, * from ...
Union All
select id2 ad id,  * from ...
order by id) as t
order by t.id

答案 3 :(得分:0)

使用northwind

select OrderID, ProductID from [Order Details] a
UNION all
Select OrderID, EmployeeID from Orders b
order by a.ProductID

答案 4 :(得分:0)

所有这些答案都包括原始海报的尝试只是简单的混乱或过于复杂。这里有一个简单易懂的解释:

How to order by with union

with,

“只需​​写下

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

order by应用于完整的结果集 “ 只需在这里使用UNION ALL而不是UNION。