为每位客户选择3个最新订单

时间:2010-05-07 18:23:15

标签: sql-server-2005

这是我收集客户订单的表CusOrder

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个最新订单 我怎么能这样做

抱歉我的英文不好

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

应该有效。没有使用这种确切的数据库结构进行测试,但类似的东西。

答案 2 :(得分:0)

“纯粹的”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

我不确定你需要什么输出,但这不应该很难。