2010-05-07 56 views
2

這裏是我的表CusOrder收集客戶訂單選擇3最新的順序爲每個客戶

OrderID  Cus_ID Product_ID NumberOrder  OrderDate 
    1  0000000001  9   1  6/5/2553 0:00:00 
    2  0000000001  10   1  6/5/2553 0:00:00 
    3  0000000004  9   2  13/4/2553 0:00:00 
    4  0000000004  9   1  17/3/2553 0:00:00 
    5  0000000002  9   1  22/1/2553 0:00:00 
    7  0000000005  9   1  16/12/2552 0:00:00 
    8  0000000003  9   3  13/12/2552 0:00:00 
    10  0000000001  9   2  19/11/2552 0:00:00 
    11  0000000003  9   2  10/11/2552 0:00:00 
    12  0000000002  9   1  23/11/2552 0:00:00 

,我需要選擇3最新的順序爲每一個客戶,我需要所有的客戶 所以它會顯示每個客戶和他的/她的3最新的順序 我怎麼能做到這一點

對不起我的英文不好

回答

0
WITH Temp AS 
(
    SELECT *, (ROW_NUMBER() OVER (PARTITION BY Cus_ID ORDER BY OrderDate DESC)) AS Number 
    FROM CusOrder 
) 
SELECT * FROM Temp WHERE Number <= 3 

應該工作。沒有測試這個確切的數據庫結構,但類似的東西。

+0

看起來更容易閱讀謝謝 – Ratiug 2010-05-07 20:47:54

2

這CTE應該爲你工作:

;with cteTop3PerGroup as 
(
    select row_number() over(partition by Cus_ID order by OrderDate DESC) as RN 
      , * 
    from CusOrder 
) 
select * from cteTop3PerGroup 
where RN <= 3 
+0

謝謝!它的工作 – Ratiug 2010-05-07 18:35:23

+0

有趣的是,在實際嘗試之前,我想我可以不用公共表格表達。 T-SQL雖然很瑣碎......但奇怪的是,你的帖子直到完成後才顯示出來。 – Thorarin 2010-05-07 18:41:36

0

「Pure」SQL解決方案。


With Customers As (
    Select Cus_ID From test Group By Cus_ID 
    ), 
TopLastOrders as (
    Select o.Cus_ID, Max(OrderDate) as OrderDate 
    From test o Inner Join Customers c on c.Cus_ID = o.Cus_ID 
    Group By o.Cus_ID 
    ), 
TopSecondOrders as (
    Select o.Cus_ID, Max(OrderDate) as OrderDate 
    From test o Inner Join Customers c on c.Cus_ID = o.Cus_ID 
    Where Not Exists (Select 1 From TopLastOrders Where Cus_ID=o.Cus_ID And OrderDate=o.OrderDate) 
    Group By o.Cus_ID 
    ), 
TopThirdOrders as (
    Select o.Cus_ID, Max(OrderDate) as OrderDate 
    From test o Inner Join Customers c on c.Cus_ID = o.Cus_ID 
    Where Not Exists (Select 1 From TopLastOrders Where Cus_ID=o.Cus_ID And OrderDate=o.OrderDate) 
     And Not Exists (Select 1 From TopSecondOrders Where Cus_ID=o.Cus_ID And OrderDate=o.OrderDate) 
    Group By o.Cus_ID 
    )

Select c.Cus_ID, t1.OrderDate, t2.OrderDate, t3.OrderDate From Customers c
Left Outer Join TopLastOrders t1 on t1.Cus_ID = c.Cus_ID Left Outer Join TopLastOrders t2 on t2.Cus_ID = c.Cus_ID Left Outer Join TopLastOrders t3 on t3.Cus_ID = c.Cus_ID

Order By c.Cus_ID

我不知道你需要什麼輸出,但這個應該不難。

+0

這是另一種解決方案,當我不使用SQL Server 2005時可以使用是的? 抱歉我的英文不好 – Ratiug 2010-05-07 20:54:06

相關問題