简体   繁体   中英

How to create a time series from effective dates in SQL

The first table named 'Template' has an Effective Date and Configuration columns as given below:

The second table is a fiscal calendar containing Dates, Fiscal Week, and Fiscal Year.

The first Effective date falls on Fiscal week 39, while the next effective date falls on Fiscal week 42. This means that Fiscal Week 40 and 41 should have the same configurations as Fiscal week 39. I need an output which reflects this. I've written the following snippet but the output is incorrect and shows Configuration D in fiscal week 42.

SELECT * 
FROM ( 
  SELECT a.FiscalYear, a.FiscalWeek, EffectiveDate, Configuration,
         ROW_NUMBER() OVER (PARTITION BY CONCAT(FiscalYear,FiscalWeek,EffectiveDate,Configuration) ORDER BY EffectiveDate ) AS rn 
  FROM [Template], 
       [FiscalCalendar] AS a 
  WHERE AND a.FiscalDate BETWEEN '2019-10-27' AND '2019-11-17' 
    AND EffectiveDate BETWEEN '2019-10-27' AND '2019-11-17' 
    AND EffectiveDate = a.FiscalDate 
) AS t WHERE t.rn = 1

The use of square braces suggests that the database is SQL Server, so I will assume that is the case.

For each row in the calendar table you need the most recent configuration. This sounds like a lateral join, ie apply :

select cw.*, t.configuration
from (select c.fiscalweek, c.fiscalyear, min(c.fiscaldate) as weekstart
      from calendar c
      group by c.fiscalweek, c.fiscalyear
     ) cw cross apply
     (select top (1) with ties t.*
      from template t
      where t.effectivedate <= cs.weekstart
      order by t.effectivedate desc
     ) t;

One "tricky" part here is that the results are by week and not by day. There may be a simpler way to extract weeks from the Calendar table than using aggregation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM