2017-02-27 80 views
1

SQL Server 2014中,我使用Northwind作爲示例數據庫,並使用Orders表。使用Top with Union全部

選擇第一行:

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

它們不同,因爲您在第一個查詢中沒有使用「ORDER BY」。如果沒有'ORDER BY',那麼每次'TOP 1'的結果都不能保證一致。如果你想獲得第一個結果,你需要做一個'ORDER BY orderID ASC'。 – Siyual

+0

@Siyual,它不起作用,如果我在第一個查詢中使用了「Order by OrderID ASC」,我得到:'關鍵字'union'附近的語法錯誤。 ' –

回答

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 

,因爲是在最後的聯合評估,除非它被包裹的子查詢中的順序。

您已經知道解決方法,所以我沒有提及它。

+0

感謝您的回答,這是我的預期,最後一點是它的記錄? –