返回每个客户的最近4个订单

时间:2014-04-16 22:48:26

标签: sql sql-server sql-server-2012

我想为每个CustomerID返回最近的4个。到目前为止,我有:

使用Northwind_2012

SELECT CustomerID, OrderDate
FROM Orders
ORDER BY CustomerID;

从这里开始,我想将其限制为每个CustomerID最近4个OrderDate。为了达到这个目的,我从哪里开始,因为我也尝试过使用PARTITION BY和ROW_NUMBER,但还没有能够完成它。

CustomerID OrderDate
ALFKI 2007-08-25 00:00:00.000
ALFKI 2007-10-03 00:00:00.000
ALFKI 2007-10-13 00:00:00.000
ALFKI 2008-01-15 00:00:00.000
ALFKI 2008-03-16 00:00:00.000
ALFKI 2008-04-09 00:00:00.000
ANATR 2008-03-04 00:00:00.000
ANATR 2007-11-28 00:00:00.000
ANATR 2007-08-08 00:00:00.000
ANATR 2006-09-18 00:00:00.000
ANTON 2006-11-27 00:00:00.000
ANTON 2007-04-15 00:00:00.000

3 个答案:

答案 0 :(得分:1)

您可以使用row_number(),使用子查询或CTE执行此操作:

SELECT CustomerID, OrderDate
FROM (SELECT o.*,
             ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate DESC) as seqnum
      FROM Orders
     ) o
WHERE seqnum <= 4
ORDER BY CustomerID;

答案 1 :(得分:0)

经过测试,有效:

(假设&#34; OrderID&#34;主键:

SELECT CustomerId, OrderDate
FROM Orders as ExtOrders
WHERE OrderId IN (
     SELECT TOP 4 OrderId
     FROM Orders
     WHERE CustomerId LIKE ExtOrders.CustomerId
     ORDER BY OrderDate DESC)
ORDER BY CustomerId; -- Might not work in SQLFiddle if CustomerId is text

SQLFiddle

答案 2 :(得分:-1)

编辑,我没有彻底阅读这个问题。试试这个:

Use Northwind_2012
WITH e
AS (
    SELECT ROW_NUMBER() OVER (
            PARTITION BY CustomerID ORDER BY OrderDate DESC
            ) AS rownum
        ,CustomerID
        ,OrderDate
    FROM Orders
    )
SELECT CustomerID
    ,OrderDate
FROM e
WHERE rownum <= 4

http://technet.microsoft.com/en-us/library/ms189461.aspx

SQLFiddle:http://sqlfiddle.com/#!6/afe40/11/0