sql server - Filling in missing ranges in a set -
this question on filing missing ranges of data. specifically, have result set each row contains startdate , enddate value. let's have:
start end 1/15 1/20 1/12 3/15
i need query produces adds following row data:
1/21 2/11
most other related questions filling gaps know set (like list of dates). case i'm looking start/end of missing data.
assuming meant write 1/21 instead of 2/21, here's way it:
with dates ( select '2016-01-15' dtstart, '2016-01-20' dtend union select '2016-02-12', '2016-03-15' union select '2016-03-21', '2016-04-11' ), calcs ( select dateadd(day, 1, dtend) rangestart, (select dateadd(day, -1, min(dtstart)) dates d2 d2.dtstart > d.dtend) rangeend dates d ) select * calcs c c.rangeend >= c.rangestart
the table dates
3 rows of sample dates. in thecalcs
table, rangestart
column next day after each dtend
. rangeend
column takes next dtstart
, subtracts day. finally, last row have null because there missing range after last dtend, ignore row null rangeend
value.
edit: if you're unfamiliar with
statement in code, it's cte. used here quick way create table sample data in (dates) , place store calculations (calcs).
edit2: since mentioned using join in comment, here's way that:
with dates ( select '2016-01-15' dtstart, '2016-01-20' dtend union select '2016-02-12', '2016-03-15' union select '2016-03-21', '2016-04-11' ), calcs ( select dateadd(day, 1, d1.dtend) rangestart, dateadd(day, -1, min(d2.dtstart)) rangeend dates d1 join dates d2 on d1.dtend < d2.dtstart group d1.dtend ) select * calcs datediff(day, rangestart, rangeend) >= 0
edit3: updated datediff inequality include ranges of 1 day
Comments
Post a Comment