使用Top with Union all

时间:2017-02-27 19:24:29

标签: sql-server sql-server-2014 union-all

SQL Server 2014中,我使用Northwind作为示例数据库,并使用Orders表。

选择第一行:

select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders

输出:

orderID CustomerID  EmployeeID  OrderDate   RequiredDate
10248   VINET   5   1996-07-04 00:00:00.000 1996-08-01 00:00:00.000

选择最后一行:

select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders order by orderID desc

输出:

orderID CustomerID  EmployeeID  OrderDate   RequiredDate
11077   RATTC   1   1998-05-06 00:00:00.000 1998-06-03 00:00:00.000

让我们使用Union ALL

组合第一行和最后一行
select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders
union all
select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders order by orderID desc

输出:

orderID CustomerID  EmployeeID  OrderDate   RequiredDate
10248   VINET   5   1996-07-04 00:00:00.000 1996-08-01 00:00:00.000
10248   VINET   5   1996-07-04 00:00:00.000 1996-08-01 00:00:00.000

那么为什么最后的结果没有按预期显示数据。

我知道要获得第一行和最后一行,请使用下一行: -

select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders
union all
Select * from
(
select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders order by orderID desc ) a

输出: -

orderID CustomerID  EmployeeID  OrderDate   RequiredDate
10248   VINET   5   1996-07-04 00:00:00.000 1996-08-01 00:00:00.000
11077   RATTC   1   1998-05-06 00:00:00.000 1998-06-03 00:00:00.000

但我仍然感到困惑,为什么我应该第二次选择派生表!

1 个答案:

答案 0 :(得分:3)

这个

select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders
union all
select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders order by orderID desc

实际上如下:

(select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders
union all
select top 1 orderID, CustomerID,EmployeeID,OrderDate,RequiredDate 
from orders) order by orderID desc

因为除非它包含在子查询中,否则将在union的最后一个时间计算order by。

你已经知道了解决方法,所以我没有提到它。