我想实现 Time Period Library for .NET 中可用的类似功能,但在 SQL 中。
首先,我有一个包含多行的表,其中有一个开始日期和一个结束日期,我想像这样将它们合并在一起:
然后使用该结果和另一个来自不同表的结果,我想找出它们两者之间的交集,像这样但只有 2 个输入(找到两者中都存在的句点):
一旦我有了交叉点,就可以总结一下时间了。
在这里,我提供了一个带有预期输出的 SQL Fiddle 示例:
http://sqlfiddle.com/#!18/504fa/3
最佳答案
样本数据准备
CREATE TABLE TableToCombine
([IdDoc] int IDENTITY(1,1), [IdEmployee] int, [StartDate] datetime, [EndDate] datetime)
;
INSERT INTO TableToCombine
(IdEmployee, StartDate, EndDate)
VALUES
(1, '2018-01-01 06:00:00', '2018-01-01 14:00:00'),
(2, '2018-01-01 11:00:00', '2018-01-01 19:00:00'),
(3, '2018-01-01 20:00:00', '2018-01-02 03:00:00'),
(1, '2018-01-02 06:00:00', '2018-01-02 14:00:00'),
(2, '2018-01-02 11:00:00', '2018-01-02 19:00:00')
;
CREATE TABLE TableToIntersect
([IdDoc] int IDENTITY(1,1), [OrderId] int, [StartDate] datetime, [EndDate] datetime)
;
INSERT INTO TableToIntersect
(OrderId, StartDate, EndDate)
VALUES
(1, '2018-01-01 09:00:00', '2018-01-02 12:00:00')
;
询问:
with ExpectedCombineOutput as (
select
grp, StartDate = min(StartDate), EndDate = max(EndDate)
from (
select
*, sum(iif(cd between StartDate and EndDate, 0, 1))over(order by StartDate) grp
from (
select
*, lag(EndDate) over (order by IdDoc) cd
from
TableToCombine
) t
) t
group by grp
)
select
a.grp, StartDate = iif(a.StartDate < b.StartDate, b.StartDate, a.StartDate)
, EndDate = iif(a.EndDate < b.EndDate, a.EndDate, b.EndDate)
from
ExpectedCombineOutput a
join TableToIntersect b on a.StartDate <= b.EndDate and a.EndDate >= b.StartDate
在 CTE 中组合了相交的时间间隔。然后加入你的 intersectTable 以找到重叠的时期。如果
a.StartDate < b.EndDate and a.EndDate > b.StartDate
,则两个期间重叠
关于sql - SQL 中时间段的交叉和合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48578248/