CREATE TABLE #products (
productId INT,
regionId INT,
date DATETIME,
active BIT
);
INSERT INTO #products VALUES
(1,20,'10/10/2020',1),(1,20,'12/10/2022',0),(1,20,'5/8/2023',1),
(2,20,'11/11/2020',0),(2,20,'12/12/2022',1),(2,20,'5/8/2023',0),
(3,20,'10/10/2020',1),(3,20,'12/10/2022',0),(3,20,'5/8/2023',1),
(4,20,'01/01/2020',1),
(5,20,'01/01/2020',0);
SELECT *, LEAD(date) OVER (PARTITION BY productId ORDER BY date) nextdate
FROM #products;
productId |
regionId |
date |
active |
nextdate |
1 |
20 |
2020-10-10 00:00:00.000 |
True |
2022-12-10 00:00:00.000 |
1 |
20 |
2022-12-10 00:00:00.000 |
False |
2023-05-08 00:00:00.000 |
1 |
20 |
2023-05-08 00:00:00.000 |
True |
null |
2 |
20 |
2020-11-11 00:00:00.000 |
False |
2022-12-12 00:00:00.000 |
2 |
20 |
2022-12-12 00:00:00.000 |
True |
2023-05-08 00:00:00.000 |
2 |
20 |
2023-05-08 00:00:00.000 |
False |
null |
3 |
20 |
2020-10-10 00:00:00.000 |
True |
2022-12-10 00:00:00.000 |
3 |
20 |
2022-12-10 00:00:00.000 |
False |
2023-05-08 00:00:00.000 |
3 |
20 |
2023-05-08 00:00:00.000 |
True |
null |
4 |
20 |
2020-01-01 00:00:00.000 |
True |
null |
5 |
20 |
2020-01-01 00:00:00.000 |
False |
null |
DECLARE @from DATE = '03/01/2023';
DECLARE @till DATE = '03/31/2023';
WITH cte AS (
SELECT *, COALESCE(LEAD(date) OVER (PARTITION BY productId ORDER BY date),
DATEADD(dd, 1, @till)) nextdate
FROM #products
)
SELECT *
FROM cte
WHERE date <= @till
AND @from <= nextdate
AND active = 1;
productId |
regionId |
date |
active |
nextdate |
2 |
20 |
2022-12-12 00:00:00.000 |
True |
2023-05-08 00:00:00.000 |
4 |
20 |
2020-01-01 00:00:00.000 |
True |
2023-04-01 00:00:00.000 |
fiddle
If you want to process your data for each region separately then expand PARTITION BY expression accordingly.