TSQL Finding Order that occurred in 3 consecutive months

前端 未结 4 702
悲哀的现实
悲哀的现实 2021-01-05 00:56

Please help me to generate the following query. Say I have customer table and order table.

Customer Table

CustID CustName

1      AA     
2      BB
         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 01:33

    Edit: Got rid or the MAX() OVER (PARTITION BY ...) as that seemed to kill performance.

    ;WITH cte AS ( 
    SELECT    CustID  ,
              OrderDate,
              DATEPART(YEAR, OrderDate)*12 + DATEPART(MONTH, OrderDate) AS YM
     FROM     Orders
     ),
     cte1 AS ( 
    SELECT    CustID  ,
              OrderDate,
              YM,
              YM - DENSE_RANK() OVER (PARTITION BY CustID ORDER BY YM) AS G
     FROM     cte
     ),
     cte2 As
     (
     SELECT CustID  ,
              MIN(OrderDate) AS Mn,
              MAX(OrderDate) AS Mx
     FROM cte1
    GROUP BY CustID, G
    HAVING MAX(YM)-MIN(YM) >=2 
     )
    SELECT     c.CustName, o.OrderDate, YEAR(o.OrderDate) AS YEAR
    FROM         Customers AS c INNER JOIN
                          Orders AS o ON c.CustID = o.CustID
    INNER JOIN  cte2 c2 ON c2.CustID = o.CustID and o.OrderDate between Mn and Mx
    order by c.CustName, o.OrderDate
    

提交回复
热议问题