If there are relatively few periodt lines, then there is an option that can be quite effective.
Convert periodt to a From / To table of ranges using subqueries or CTE. (Obviously, performance depends on how efficiently this initial step can be completed, so a small number of periodt lines is periodt .) Then connecting to dailyt will be extremely efficient. For instance.
;WITH PIds AS ( SELECT ROW_NUMBER() OVER(ORDER BY PDate) RN, * FROM @periodt ), PRange AS ( SELECT f.PDate AS FromDate, t.PDate as ToDate, f.PVal FROM PIds f LEFT OUTER JOIN PIds t ON t.RN = f.RN + 1 ) SELECT d.*, p.PVal FROM @dailyt d LEFT OUTER JOIN PRange p ON d.DDate >= p.FromDate AND (d.DDate < p.ToDate OR p.ToDate IS NULL) ORDER BY 1 DESC
If you want to try a query, the following fetch data using table variables. Note. I added an extra line to dailyt to demonstrate periodt entries with a shorter date.
DECLARE @dailyt table ( DDate date NOT NULL, DVal float NOT NULL ) INSERT INTO @dailyt(DDate, DVal) SELECT '20140522', 10 UNION ALL SELECT '20140521', 9.5 UNION ALL SELECT '20140520', 9 UNION ALL SELECT '20140519', 8 UNION ALL SELECT '20140518', 7.5 UNION ALL SELECT '20140517', 6.5 DECLARE @periodt table ( PDate date NOT NULL, PVal int NOT NULL ) INSERT INTO @periodt SELECT '20140521', 2 UNION ALL SELECT '20140518', 1
source share