【发布时间】:2020-04-23 10:53:02
【问题描述】:
我有这个问题:
select
sth.Id,
sth.CreatedDateTime,
EndDateTime = Lead(sth.CreatedDateTime, 1) over (partition by sth.Id order by sth.Id, sth.CreatedDateTime)
from
Sth as sth
order by
sth.Id, sth.CreatedDateTime
返回这些结果:
Id StartDateTime EndDate
--------------------------------------------------------------------
2746743 2019-11-20 14:35:05.5841266 NULL
2746744 2019-11-20 14:35:05.5841266 NULL
3 2018-06-25 23:35:12.2799952 2018-06-26 09:57:27.8943163
13 2018-06-26 09:57:27.8943163 2018-06-26 10:41:19.2973307
我被要求更新上述查询,将带有Id=3 的行分成两行。
含义:如您所见,Id 3 的记录始于23:35 and ends the **next day** at 09:57
我需要它来将这条记录分成两部分。
第一个应该来自23:35 -> 23:59
下面的应该来自00:00 -> 09:57
如果记录跨越一天以上。什么都不需要做。最终解决方案应该能够为历史表工作。 超过 300 万行。
所以记录应该是这样的
Id StartDateTime EndDateTime
3 2018-06-25 23:35:12.2799952 2018-06-25 23:59:59.000000
3 2018-06-26 00:00:00.0000000 2018-06-26 09:57:27.8943163
我希望这是有道理的!
所有其他记录都会产生类似的结果。有些记录不需要拆分。
【问题讨论】:
-
如果一条记录跨越两天以上怎么办?你用的是什么数据库?请适当标记。
-
我们可以看到您用于构建查询结果的数据吗?
-
@JMabee 我已经提供了模拟数据。很小。预计其他行也会有类似的结果。你需要更多吗?
标签: sql sql-server date