Reputation: 143
I have a table:
startdate enddate other_columns
1956-05-06 00:00:00.000 1960-04-05 00:00:00.000 myvalues
I need a query that will return the results as:
startdate enddate other_columns
1956-05-06 00:00:00.000 1956-12-31 00:00:00.000 myvalues
1957-01-01 00:00:00.000 1957-12-31 00:00:00.000 myvalues
1958-01-01 00:00:00.000 1958-12-31 00:00:00.000 myvalues
1959-01-01 00:00:00.000 1959-12-31 00:00:00.000 myvalues
1960-01-01 00:00:00.000 1960-04-05 00:00:00.000 myvalues
Basically a query that will explode the rows into yearly results. I need the start and end dates to be retained.
Upvotes: 4
Views: 8822
Reputation: 6103
The query is quite simple
SELECT CASE WHEN yrStart<it.startdate THEN it.startdate ELSE yrStart END AS startdate,
CASE WHEN yrEnd>it.enddate THEN it.enddate ELSE yrEnd END AS enddate,
other_columns
FROM #InputTABLE it
CROSS APPLY
(SELECT datefromparts(yr, 1, 1) yrStart, datefromparts(yr, 12, 31) yrEnd
FROM dbo.yearTable
WHERE yr >= datepart(year, it.startdate) AND yr <= datepart(year, it.enddate)
)years;
all you need is a yearTable with numbers 1..9999 (aka Tally table). You should not have numbers outside of this range in this table, otherwise you would meet some nasty conversion errors.
Upvotes: 1
Reputation: 854
CREATE TABLE #InputTABLE
(
startdate DATETIME,
enddate DATETIME,
other_columns varchar(20)
)
INSERT INTO #InputTABLE VALUES('1956-05-06','1960-04-05','myvalues');
SELECT * FROM #InputTABLE
Output:
startdate enddate other_columns
1956-05-06 00:00:00.000 1960-04-05 00:00:00.000 myvalues
Query:
CREATE TABLE #OutputTABLE
(
startdate DATETIME,
enddate DATETIME,
other_columns varchar(20)
)
DECLARE @cnt int
DECLARE @startDate datetime
DECLARE @endDate datetime
DECLARE @incr int
DECLARE @tempDate datetime
SET @startDate=(Select startdate from #InputTABLE)
SET @endDate=(Select enddate from #InputTABLE)
SET @cnt=DATEDIFF(yy,@startDate,@endDate)
SET @incr=0
SET @tempDate=DATEADD(yy,@incr,Cast(@startDate As datetime))
WHILE @cnt>=0
BEGIN
IF @cnt = 0
BEGIN
INSERT INTO #OutputTABLE VALUES(@tempDate,@endDate,'myvalues');
END
ELSE
BEGIN
insert into #OutputTABLE values(@tempDate,DATEADD(yy, DATEDIFF(yy,0,@tempDate)+1, -1),'myvalues');
END
SET @tempDate=DATEADD(yy,@incr+1,DATEADD(yy,DATEDIFF(yy,0,@startDate),0))
SET @cnt=@cnt-1
SET @incr=@incr+1
END
Result : SELECT * FROM #OutputTABLE;
startdate enddate other_columns
1956-05-06 00:00:00.000 1956-12-31 00:00:00.000 myvalues
1957-01-01 00:00:00.000 1957-12-31 00:00:00.000 myvalues
1958-01-01 00:00:00.000 1958-12-31 00:00:00.000 myvalues
1959-01-01 00:00:00.000 1959-12-31 00:00:00.000 myvalues
1960-01-01 00:00:00.000 1960-04-05 00:00:00.000 myvalues
Upvotes: 3