您能否帮助您确定生成输出表的方式,如下图所示。这是我需要的成员资格/差距棘手处理的一部分。无法弄清楚如何为每个提示日期输入EACH Cust_ID。谢谢
示例代码:(*最后选择需要改进)]
CREATE TABLE #test (Cust_ID Varchar(14), Contr_ID INT, ENR_START date, ENR_END date)
INSERT INTO #test values (1, 1, '2018-1-2', '2018-01-5'), (1, 2, '2018-01-7', '2018-1-8'),
(2, 1, '2018-01-6', '2019-1-10') ----- select * from #test
select top (DATEDIFF(DAY, @Period_Start, @Period_End + 1)) ----- create tally
DATEADD(dd,ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1,@Period_Start) dt
into #c -- select * from #c -- 10 days
from master..spt_values
SELECT t.*, c.dt
FROM #c c
left JOIN #test t on c.dt between t.ENR_START and t.ENR_END
order by 1, 5
我认为这是您想要的逻辑:
select cu.cust_id, c.dt, t.*
from (select distinct cust_id from test) cu join
c
on c.dt between '2018-01-01' and '2018-01-10' left join
test t
on t.cust_id = cu.cust_id and c.dt between enr_start and enr_end
order by cu.cust_id, c.dt;
想法是生成所有cust_id
/日期组合,然后将left join
转换为原始数据以获取任何匹配项。
Here是db <>小提琴。