Hi,
(1) ISSUE! What if the CreatedDate is 2022-01-30 and you have a gap in Feb 2022... Which Date do you want to get as there is no 2022-02-30 ?!? Your recruitment us full with holes
(2) it is not well clear why you use the month as the parameter for the gaps. In your description if I have the date 2022-01-31 and next one is 2022-04-01 then you fill the date 2022-02-31 and 2022-03-31 and treat as two months gaps. But if you have date 2022-01-31 and next one is 2022-03-31 then you fill only 2022-02-31 and this one treated as one month gap even so the number of days is almost the same as in the first case. seems strange recruitment to me
If you want to deal with months that you should probably use only months (for example use first of each month).
There is no option to cover your exact recruitment as I explain above.
Here is a solution which provide the first day of the month for the missing gaps.
;With Dates as (
select TOP 1000 D = DATEADD(Month, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), CONVERT(DATE,'2000-01-01'))
FROM sys.all_objects t1
CROSS JOIN sys.all_objects t2
),
CTE as (
SELECT t.PartId, t.LeadValue, t.CreatedDate,
L = LEAD(t.CreatedDate, 1,DATEADD(MONTH,1, GETDATE())) OVER (PARTITION BY t.PartId ORDER BY t.CreatedDate)
FROM Parts t
)
SELECT t.PartId, t.LeadValue, CreatedDate = d.D--, t.CreatedDate, t.L
FROM CTE t
LEFT JOIN Dates d ON d.D >= EOMONTH(t.CreatedDate) and d.D < EOMONTH(t.L)
GO
The following solution use the date as you asked and if it does not exists then it use the first day of the month
;With Dates as (
select TOP 1000 D = DATEADD(Month, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), CONVERT(DATE,'2000-01-01'))
FROM sys.all_objects t1
CROSS JOIN sys.all_objects t2
),
CTE as (
SELECT t.PartId, t.LeadValue, t.CreatedDate,
L = LEAD(t.CreatedDate, 1,DATEADD(MONTH,1, GETDATE())) OVER (PARTITION BY t.PartId ORDER BY t.CreatedDate)
FROM Parts t
)
SELECT t.PartId, t.LeadValue--, t.CreatedDate
,CreatedDate = CASE
WHEN DATEPART(DAY,t.CreatedDate) <= DATEPART(DAY,EOMONTH(d.D))
THEN DATEADD(DAY, DATEPART(DAY,t.CreatedDate)-1, d.D)
ELSE EOMONTH(d.D)
END
FROM CTE t
LEFT JOIN Dates d ON EOMONTH(d.D) >= EOMONTH(t.CreatedDate) and EOMONTH(d.D) < EOMONTH(t.L)
GO
----------
Ronen Ariely
Personal Site | Blog | Facebook | Linkedin