orderId, orderDate, customerId are the relevant fields here.
A customer may have more than 1 5-day streak.
What I want the output to look like is something like this
customerID startDate endDate numDays 1 2020/01/01 2020/01/05 5 1 2020/10/1 2020/10/10 10 101 2020/04/10 2020/04/15 6
So far, this is what I have:
;
with t1 as (
select distinct o.idcustomer,orderdate, dateadd(dd,1,orderdate) nextOrderDate, 1 as tday, orderstatus
from orders o
join customers c on c.idcustomer=o.idcustomer
where orderstatus in (3,4) and c.customertype=0
), t2 as (
select * from t1
union all
select o2.idcustomer, o2.orderdate, dateadd(dd,1,o2.orderdate), o.tday+1, o2.orderstatus
from t1 o2
join t2 o on o2.idcustomer=o.idcustomer and o2.orderdate=o.nextOrderDate and o2.orderstatus in (3,4)
)
--select idcustomer, max(tday) DaysInARow, min(orderDate) StartDate, max(orderdate) endDate
select idcustomer, dateadd(dd,-5,min(orderdate)) firstOrderDate, max(orderdate) lastOrderDate
from t2
where tday>=5
group by idcustomer, tday
order by idcustomer