質問

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.

enter image description here

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:

enter image description here

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:

enter image description here

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.

役に立ちましたか?

解決

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;

他のヒント

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.

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top