sql - SQL 中时间段的交叉和合并

标签 sql sql-server time period

我想实现 Time Period Library for .NET 中可用的类似功能,但在 SQL 中。

首先,我有一个包含多行的表,其中有一个开始日期和一个结束日期,我想像这样将它们合并在一起:

Combination

然后使用该结果和另一个来自不同表的结果,我想找出它们两者之间的交集,像这样但只有 2 个输入(找到两者中都存在的句点):

Intersection

一旦我有了交叉点,就可以总结一下时间了。

在这里,我提供了一个带有预期输出的 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/

相关文章:

php - 如何同时按数字和字母顺序对 varchar 查询列进行排序

variables - 批量添加时间分钟数(使用算术)

mysql - 错误使用内连接函数/分组函数?

mysql - SQL 方程当前减去其他年份?

sql - 首次运行后 Access 删除查询的 SQL 内容

android - 知旧时

Flash导出/发布时间

sql - 检查列是否在 PL/SQL 函数中具有特定条目

c# - 使用 C# 执行 SSIS 包时出错

sql - 如何获取表变量的行数?