代码之家  ›  专栏  ›  技术社区  ›  scottm

有没有方法可以透视客户ID和他们最近的订单日期?

  •  2
  • scottm  · 技术社区  · 14 年前

    我有一个查询,告诉我所有客户及其最后三个订单日期。

    前任:

    CustomerId DateOrdered
    167 2006-09-16 01:25:38.060
    167 2006-09-21 13:11:53.530
    171 2006-08-31 15:19:22.543
    171 2006-09-01 13:30:54.013
    171 2006-09-01 13:34:36.483
    178 2006-09-04 11:36:19.983
    186 2006-09-05 12:50:27.153
    186 2006-09-05 12:51:08.513
    

    我想知道是否有一种方法可以让我将它旋转到如下显示:

    [CustomerId]    [Most Recent] [Middle] [Oldest]
    '167'   '2006-09-21 13:11:53.530'   '2006-09-16 01:25:38.060'   'NULL'
    '171'    '2006-09-01 13:34:36.483'   '2006-09-01 13:30:54.013'   '2006-08-31 15:19:22.543'
    '178'   '2006-09-04 11:36:19.983'   NULL    NULL
    '186'   '2006-09-05 12:51:08.513'   '2006-09-05 12:50:27.153'   NULL    
    
    2 回复  |  直到 14 年前
        1
  •  4
  •   Martin Smith    14 年前
    ;WITH YourQuery As
    (
    SELECT CustomerId, DateOrdered,
    ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY DateOrdered DESC) AS RN
    FROM Orders
    )
    select [CustomerId],
    MAX(CASE WHEN RN=1 THEN DateOrdered END) AS  [Most Recent] ,
    MAX(CASE WHEN RN=2 THEN DateOrdered END) AS  [Middle] ,
    MAX(CASE WHEN RN=3 THEN DateOrdered END) AS  [Oldest] 
    FROM YourQuery
    WHERE RN<=3
    GROUP BY [CustomerId]
    
        2
  •  0
  •   AllenG    14 年前

    警告:未测试

    我想你在找这样的东西。特定的join和where子句可能需要一些工作,但基本上,您只是将表重新连接起来,以便每次获得一个日期。

    SELECT C.CUSTOMERID, C.DATEORDERED, C2.DATEORDERED, C3.DATEORDERED
    FROM CUSTOMER C
    INNER JOIN CUSTOMER C2 ON C.CUSTOMERID = C2.CUSTOMERID
    INNER JOIN CUSTOMER C3 ON C.CUSTOMERID = C3.CUSTOMERID
    WHERE C.DATEORDERED = MAX(C.DATEORDERED)
    AND C2.DATEORDERED < C.DATEORDERED AND 
        (C3.DATEORDERED IS NULL OR C2.DATEORDERED >     C3.DATEORDERED)