SQL calculate time interval between first and second purchase for each Client

时间:2018-03-25 19:07:32

标签: sql sql-server common-table-expression

I want to get the time interval between first and second purchase for each Client, my query inside the CTE works, but get error msg below. How to work around, should I use temporary table or create a VIEW?

my inner query result

Client  PurchaseDate    nextBuy   IntervalFirstSecond   RM
ABC       2014/10/13    2015/9/15     337                1
ABC       2015/9/15    2015/11/29      75                2
ABC       2015/11/29    2016/9/17      293               3
ABC        2016/9/17    2016/9/17       0                4
EFG        2013/8/18    2014/5/21      276               1
EFG        2014/5/21    2015/2/4       259               2
EFG         2015/2/4    2016/3/20      410               3


WITH myCTE AS 
(
    SELECT Client, 
           PurchaseDate, 
           LEAD(PurchaseDate) OVER (ORDER BY Client) nextBuy,
           datediff(DD,PurchaseDate,(LEAD(PurchaseDate) OVER (ORDER BY Client))) IntervalFirstSecond,
           row_number() over (PARTITION BY CLIENT ORDER BY CLIENT) RM
     FROM Transactions 
     group by Client, PurchaseDate, [Paid ] 
     ORDER BY Client
)
SELECT  *  FROM myCTE where RM = 1

Error Msg:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

2 个答案:

答案 0 :(得分:2)

If you want to get that result for each client you must add PARTITION BY and to get the 1st and 2nd you must order by PurchaseDate:

WITH myCTE AS 
(
    SELECT Client, 
           PurchaseDate, 
           LEAD(PurchaseDate) OVER (PARTITION BY Client ORDER BY PurchaseDate) AS nextBuy,
           row_number()       OVER (PARTITION BY CLIENT ORDER BY PurchaseDate) AS RM
     FROM Transactions 
     -- probably no GROUP BY needed
     -- group by Client, PurchaseDate, [Paid ] 
)
SELECT Client, 
       PurchaseDate, 
       nextBuy,
       datediff(DD,PurchaseDate, nextBuy) AS Interval_1st_2nd,
FROM myCTE
where RM = 1

答案 1 :(得分:1)

remove ORDER BY Client, then it works. Credit from user @Máté Juhász

WITH myCTE AS 
(
    SELECT Client, 
           PurchaseDate, 
           LEAD(PurchaseDate) OVER (ORDER BY Client) nextBuy,
           datediff(DD,PurchaseDate,(LEAD(PurchaseDate) OVER (ORDER BY Client))) IntervalFirstSecond,
           row_number() over (PARTITION BY CLIENT ORDER BY CLIENT) RM
     FROM Transactions 
     group by Client, PurchaseDate, [Paid ] 
)
SELECT  *  FROM myCTE where RM = 1