从SQL Server数据库中选择实体交互

时间:2017-10-09 21:37:56

标签: sql sql-server

我的任务是生成SQL Server数据库中处理进入和退出区域的实体的数据报告。该报告用于确定一对实体何时在一个区域内相互作用,报告它们相互作用的持续时间,以及交互的开始和结束时间。

AreaEvents表的架构如下所示:

EventId uniqueidentifier,
EntityId uniqueidentifier,
AreaId uniqueidentifier,
EnterTime datetime,
ExitTime datetime

这是我提出的SELECT声明,但性能有点欠缺。我必须添加一个DISTINCT子句,与CASE WHEN a.EntityId < b.EntityId配对,用于选择EntityIds以防止反向重复行出现在结果数据集中。

SELECT DISTINCT
    a.AreaId, 
    -- Select the latest enter time from the entity interaction
    CASE
        WHEN a.EnterTime >= b.EnterTime THEN a.EnterTime
        ELSE b.EnterTime
    END as StartTime,

    -- Select the earliest exit time from the entity interaction
    CASE
        WHEN a.ExitTime <= b.ExitTime THEN a.ExitTime
        ELSE b.ExitTime
    END as EndTime,

    -- Diff the start time and end time to get the duration
    DATEDIFF(MILLISECOND,   
        CASE
            WHEN a.EnterTime >= b.EnterTime THEN a.EnterTime
            ELSE b.EnterTime
        END,    
        CASE
            WHEN a.ExitTime <= b.ExitTime THEN a.ExitTime
            ELSE b.ExitTime
        END) as Duration,

    -- So we can distinctly select the rows, we need to make sure the 
    -- same entities are always selected for entity 1 and entity 2 for
    -- the same interactions.
    CASE WHEN a.EntityId < b.EntityId 
        THEN a.EntityId 
        ELSE b.EntityId 
    END as EntityId1,

    -- So we can distinctly select the rows, we need to make sure the 
    -- same entities are always selected for entity 1 and entity 2 for
    -- the same interactions.
    CASE WHEN a.EntityId < b.EntityId 
        THEN b.EntityId 
        ELSE a.EntityId 
    END as EntityId2
FROM AreaEvents a
JOIN AreaEvents b
ON
    a.EntityId != b.EntityId AND
    a.AreaId = b.AreaId AND
    a.EnterTime <= b.ExitTime AND 
    a.ExitTime >= b.EnterTime 

这里的CASE WHEN表现是否膨胀,或者归因于此处的FROMWHERE条款? SQL不是我最强的诉讼;是否有更好的替代方法?

0 个答案:

没有答案