2013-08-26 80 views
1

我試圖將基於OrderDateOrder表的最後5行與列名firstnameCustomer表中取出。選擇連接查詢中的最後5行SQL Server 2008

以下查詢顯示Order表中的所有值,而不是最後5行。

SELECT 
    A.[FirstName], B.[OrderId], B.[OrderDate], B.[TotalAmount], B.[OrderStatusId] 
FROM 
    [schema].[Order] B 
OUTER APPLY 
    (SELECT TOP 5 * 
    FROM [schema].[Customer] A 
    WHERE B.[CustomerId] = 1 
     AND A.[CustomerId] = B.[CustomerId] 
    ORDER BY 
     B.[OrderDate] DESC) A 

在我使用TOPDESC的邏輯中的任何錯誤?

+0

大家都知道如何找到底部5.有人可以告訴上述查詢錯誤嗎? –

+0

您從查詢中獲得的輸出是什麼? –

+0

您是否需要系統中的最後五個訂單或每個客戶最後五個訂單? –

回答

3

如果你想獲得最後的5行Order表的,你爲什麼要TOPCustomer表?

SELECT TOP 5 A.[FirstName],B.[OrderId],B.[OrderDate],B.[TotalAmount],B.[OrderStatusId] 
FROM [schema].[Order] B 
LEFT JOIN [schema].[Customer] A ON A.[CustomerId]=B.[CustomerId] 
WHERE B.[CustomerId]=1 
ORDER BY B.[OrderDate] DESC 
1
;WITH MyCTE AS 
(

    SELECT A.[FirstName], 
      B.[OrderId], 
      B.[OrderDate], 
      B.[TotalAmount], 
      B.[OrderStatusId], 
      ROWNUMBER() OVER (ORDER BY B.[OrderDate] DESC) AS RowNum 
    FROM [schema].[Order] B 
      OUTER APPLY 
      ( 
       SELECT TOP 5 * 
       FROM [schema].[Customer] A 
       WHERE B.[CustomerId]=1 
         AND A.[CustomerId]=B.[CustomerId] 
       ORDER BY 
       B.[OrderDate] DESC     
      )  A 
) 

SELECT [FirstName], 
     [OrderId], 
     [OrderDate], 
     [TotalAmount], 
     [OrderStatusId] 
FROM MyCTE 
WHERE RowNum <= 5 
1

雖然可以使用OUTER APPLY,我覺得row_number()這樣的疑問:

SELECT A.[FirstName],B.[OrderId],B.[OrderDate],B.[TotalAmount],B.[OrderStatusId] 
FROM [schema].[Order] B join 
     (select A.*, row_number() over (partition by CustomerId order by OrderDate desc) as seqnum 
     from [schema].[Customer] A 
     where A.[CustomerId] = 1 -- AND A.[CustomerId]=B.[CustomerId] 
    ) A 
     on A.[CustomerId] = B.[CustomerId] and seqnum <= 5;