Hi @bizzi Manna
Try this query:
DECLARE @Startdate date = CAST('20210701' as datetime)
DECLARE @Enddate date = CAST('20221031' as datetime)
;WITH DateTable AS
(
SELECT @Startdate AS [date]
UNION ALL
SELECT DATEADD(MONTH, 1, [date])
FROM DateTable
WHERE DATEADD(MONTH, 1, [date]) <= @Enddate
),CTE AS
(
SELECT C.CID
,ISNULL(O.CostOrderDay_Date,C.CustomerJoinDate)AS Order_Date
,DATEADD(DAY,100,ISNULL(O.CostOrderDay_Date,C.CustomerJoinDate))AS [100_Days_Offset]
,LEAD(ISNULL(O.CostOrderDay_Date,C.CustomerJoinDate),1,DATEADD(MONTH,1,@Enddate))OVER(PARTITION BY C.CID ORDER BY O.CostOrderDay_Date) AS Next_OrderDate
FROM Customers C LEFT JOIN Customers_Orders O ON C.CID=O.CID
)
SELECT LEFT(DATENAME(MONTH,[date]),3)+'-'+DATENAME(YEAR,[date]) AS MONTH_YEAR,COUNT(CID)AS InactiveCustomerCounts
FROM DateTable D LEFT JOIN CTE C ON DATEDIFF(DAY,Order_Date,Next_OrderDate)>100
AND (DATEDIFF(MONTH,D.date,C.[100_Days_Offset])=0)
OR (DATEDIFF(MONTH,D.date,C.[100_Days_Offset])<0 AND DATEDIFF(MONTH,D.date,C.Next_OrderDate)>0)
GROUP BY [date]
Output:
Best regards,
Li Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.