I appreciate learning both those techniques.
I tried another way, and it did not work at all.
Tried to derive the boundaries from existing tstamps, but it will not work as you can have multiple boundaries between the state changes, like if a machine is down a day.
I had some issues with using a table generator.
I did my best to adapt the idea of the table generator.
select
Line
, tstamp
, case when tstamp < dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) and leadTstamp > dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) then dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0))
when tstamp < dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) and leadTstamp > dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) then dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0))
else leadTstamp end as leadTstamp
, State
from allLeadsSQ
union
select
Line
, case when tstamp < dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) and leadTstamp > dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) then dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0))
when tstamp < dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) and leadTstamp > dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) then dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0))
else leadTstamp end as tstamp
, leadTstamp
, State
from allLeadsSQ
where tstamp < dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) and leadTstamp > dateadd(hh, 7, DATEADD(dd,DATEDIFF(dd,0,tstamp),0))
or( tstamp < dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)) and leadTstamp > dateadd(hh, 19, DATEADD(dd,DATEDIFF(dd,0,tstamp),0)))