简体   繁体   中英

SQL - Creating a historical fact table from latest snapshot data

I'm currently working on an interesting problem and though I'd share it to solicit ideas.

I have a table, lets call it Table One . Each ID has an effective date range implied by datetimes (these are actually DATETIME types, even though I've presented them strangely below) Date A and Date B . So for example, ID 1 was in effect from 1-Nov until 3-Nov.

在此输入图像描述

From this table, I'd like to produce a table similar to Target Table (pictured below), where each ID/Effective Date combination is listed row-by-row:

在此输入图像描述

To accomplish this, I also have a table containing sequential dates, with the string format for the date, along with a start datetime and an end datetime:

在此输入图像描述

My experience is mostly with C# and while I could whip up a script to accomplish this, I worry that I would be hacking around what can be accomplished with pure SQL.

What you need as a calendar table - like you have but using actual DATETIME , then just join you data on to it as

SELECT c.ShortDate, t.Id, t.StartDate, t.EndDate
FROM dbo.Calendar c
JOIN tbl t ON c.ShortDate BETWEEN t.StartDate AND t.EndDate
ORDER BY c.ShortDate, t.Id

Sidenote: keep all dates as DATETIME (or related data type) and let the client format it.

you can do it with a join, but considering your data types, it's a bit convoluted. The best to do is to use, in your Table One, columns with the DATE datatype, instead of strings. Then you can do something like that :

SELECT t2.DateStr, t1.Id
FROM TableOne t1
JOIN TableTwo t2 ON t2 StartDatetime BETWEEN t1.DateA AND t1.DateB
ORDER BY t2.DateStr, t1.Id;

Here's a solution that's similar to the others. I do have a SQL Fiddle I spent too long creating, though, for what it's worth.

SELECT ds.datestr, t1.id 
FROM DateStrings ds
INNER JOIN TableOne t1 
    ON ds.startdate BETWEEN t1.startdate AND t1.EndDate
ORDER BY datestr

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