gpt4 book ai didi

sql-server - 使用 SQL 将日期范围拆分为多行

转载 作者:行者123 更新时间:2023-12-03 13:16:08 24 4
gpt4 key购买 nike

我有一张 table :

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
基本上是一个将行分解为年度结果的查询。我需要保留开始和结束日期。

最佳答案

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 @cnt=@cnt-1
SET @incr=@incr+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

关于sql-server - 使用 SQL 将日期范围拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36778537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com