处理来自多行的日期
Posted
技术标签:
【中文标题】处理来自多行的日期【英文标题】:Dealing with Dates from multiple rows 【发布时间】:2019-04-09 07:47:28 【问题描述】:我需要为具有相同 ID 值的每一行生成一个结束日期,作为下一条记录的 date-1,如果该 ID 没有下一行,则结束日期应该为空。
例如,对于 ID 513,第一行是 2008-01-01 和 2010-04-16,第二行是 2010-04-17、2011-04-25。
我不确定如何在没有光标的情况下实现这一目标。
Create Table #Temp
(
ID int,
Amount money,
StartDate datetime
)
insert into #Temp
(
ID,
Amount,
StartDate
)
select 513,240.00,'2008-01-01 00:00:00' union all
select 513,240.00,'2010-04-17 00:00:00' union all
select 513,265.00,'2011-04-26 00:00:00' union all
select 513,275.00,'2012-04-17 00:00:00' union all
select 513,285.00,'2013-04-22 00:00:00' union all
select 513,325.00,'2015-06-15 00:00:00' union all
select 513,335.00,'2017-06-15 00:00:00' union all
select 514,280.00,'2001-01-22 00:00:00' union all
select 514,280.00,'2010-06-09 00:00:00' union all
select 515,240.00,'2019-01-01 00:00:00' union all
select 515,240.00,'2010-04-17 00:00:00' union all
select 515,265.00,'2011-04-26 00:00:00' union all
select 515,275.00,'2012-04-17 00:00:00' union all
select 515,285.00,'2013-04-22 00:00:00' union all
select 515,325.00,'2015-06-15 00:00:00' union all
select 515,335.00,'2017-06-15 00:00:00'
select * from #Temp
drop table #Temp
【问题讨论】:
【参考方案1】:您可以使用LEAD()
和DATEADD()
来实现您的结果:
SELECT *, DATEADD(DAY, -1, LEAD (StartDate, 1) OVER (PARTITION BY ID ORDER BY StartDate)) AS ENDDATE
FROM #Temp
Demo on db<>fiddle
【讨论】:
【参考方案2】:您可以使用铅,它可以按照您的要求工作,
select *, lead(StartDate-1) over(partition by id order by id,startdate) as EndDate
from #Temp
【讨论】:
【参考方案3】:对于 SQL Server 2005+:
WITH CTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY StartDate) as row_num,
ID, Amount, StartDate FROM #Temp
)
SELECT
prev.ID,
prev.Amount,
prev.StartDate,
DATEADD(DAY, -1, ISNULL(prev.StartDate,1)) AS EndDate
FROM CTE prev
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
【讨论】:
【参考方案4】:select t1.* , dateadd(day,-1,t2.dt) enddate
from (select row_number()over(partition by ID order by ID) srno, ID, StartDate dt from #Temp) t1
left join (select row_number()over(partition by ID order by ID) srno, ID, StartDate dt from #Temp)t2 on t1.srno =(t2.srno-1)and t1.ID = t2.ID
【讨论】:
以上是关于处理来自多行的日期的主要内容,如果未能解决你的问题,请参考以下文章
如何合并来自多行的值,以便它们可以一起处理 - Spark scala