TSQL Finding Order that occurred in 3 consecutive months

前端 未结 4 755
悲哀的现实
悲哀的现实 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:30

    Here you go:

    select distinct
     CustName
    ,year(OrderDate) [Year]
    ,OrderDate
    from 
    (
    select 
     o2.OrderDate [prev]
    ,o1.OrderDate [curr]
    ,o3.OrderDate [next]
    ,c.CustName
    from [order] o1 
    join [order] o2 on o1.CustId = o2.CustId and datediff(mm, o2.OrderDate, o1.OrderDate) = 1
    join [order] o3 on o1.CustId = o3.CustId and o2.OrderId <> o3.OrderId and datediff(mm, o3.OrderDate, o1.OrderDate) = -1
    join Customer c on c.CustId = o1.CustId
    ) t
    unpivot
    (
        OrderDate for [DateName] in ([prev], [curr], [next])
    )
    unpvt
    order by CustName, OrderDate
    

提交回复
热议问题