2016-04-21 53 views
3

多行我有一個表:裂棗範圍內使用SQL

startdate enddate other_columns 1956-05-06 00:00:00.000 1960-04-05 00:00:00.000 myvalues

我需要一個查詢,將返回的結果爲:

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

基本上是一個查詢,將將行分解爲年度結果。我需要保留開始日期和結束日期。

謝謝!

+0

https://technet.microsoft.com/en-us/library/ ms177410%28v = sql.105%29.aspx –

+0

創建日曆表(真實或理貨)並將其與您的數據結合起來。 –

回答

3
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 

輸出:

startdate     enddate     other_columns 
    1956-05-06 00:00:00.000 1960-04-05 00:00:00.000 myvalues 

查詢:

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 @[email protected] 
    SET @[email protected]+1 

END 

結果: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