79234952

Date: 2024-11-28 18:08:09
Score: 2
Natty:
Report link

Thank you @ValNik for you help. The final query is:

DECLARE @months smallint=?; -- where ? is the number of months of continuous claim (with allowed gaps of 6 months) 
SELECT * 
FROM(
select *
  ,max(RunningMonth)over(partition by EID) maxRunningMonth
from(
select *
  ,count(case when isBreak=0 then coalesce(MonthGap,0) else 0 end)
      over(partition by EID,grN order by MonthYear) RunningMonth
  ,SUM(Lodging + coalesce(others,0.0)) 
      OVER (PARTITION BY EID,grN ORDER BY MonthYear) as RunningTotal
from(
select *
  ,sum(isBreak)
    over(partition by EID order by MonthYear) grN
from(
  SELECT c.EID
    ,c.CLMinitialDT
    ,c.MonthYear
    ,LAG(c.MonthYear) OVER (PARTITION BY c.EID ORDER BY c.MonthYear ) as PrevMth
    ,c.Lodging 
    ,c.others
  --  ,SUM(Lodging + coalesce(others,0.0)) over(partition by EId,CLMinitialDt order by MonthYear) RunningTotal
    ,COUNT(*) OVER (PARTITION BY c.EID, c.MonthYear)-1 AS Repeats1
    ,datediff(MONTH, LAG(c.MonthYear) OVER (PARTITION BY c.EID ORDER BY c.MonthYear )
                   ,c.MonthYear )  as MonthGap
    ,case when datediff(MONTH, LAG(c.MonthYear) OVER (PARTITION BY c.EID ORDER BY c.MonthYear )
                   ,c.MonthYear )>6 then 1 
     else 0 end isBreak
    ,datediff(MONTH, MIN(c.MonthYear) OVER (PARTITION BY c.EID )
                   ,MAX(c.MonthYear) OVER (PARTITION BY c.EID )) + 1 as TotalMonths 
  FROM ir_Costs c 
)a
)b
)c
)d WHERE (maxRunningMonth >= @months OR @months IS NULL)

Can be viewed here https://dbfiddle.uk/TrKMACHd

Reasons:
  • Blacklisted phrase (0.5): Thank you
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @ValNik
  • Self-answer (0.5):
  • Looks like a comment (1):
  • Low reputation (0.5):
Posted by: Jean-Marc