在记录X之前选择第一和第二记录

时间:2013-11-25 13:33:26

标签: sql sql-server

SQL Server 2008-12

我有桌子:

InteractionKey char(18)
dEventTime datetime
SeqNo int
cEventData1

每个InteractionKey会有多个条目 - 如果在同一秒内出现两个条目,则dEventTime仅会延伸到秒并且SeqNo会递增。

我需要做的是在记录之前选择第一和第二条记录

cEventData1 = 'Disconnect'

最终产品会给我一个按cEventData1分组的事件计数。

我目前正在使用游标(会暂时用光标源更新)我想使用CTE - 但我真的很难理解它们......

任何想法都将不胜感激!

使用数据样本进行更新

INTERACTIONKEY      dEventTime          SeqNo   cEventData1

100186322420130722  2013-07-22 11:50:49.000     1   EnterPassword
100186322420130722  2013-07-22 11:50:49.000     2   CheckPassword
100186322420130722  2013-07-22 11:50:49.000     3   Attendant Disconnect

查询的结果最好告诉我 - :注意此处的Action列可以简单地将“Attendant Disconnect”作为Action

cEventData1     Action                   Count
CheckPassword   Attendant Disconnect        1

以下是我根据以下答案结束的查询

    SELECT DISTINCT t1.InteractionKey,
        DisconnectTime = t1.dEventTime,
        PreviousEventTime = t2.dEventTime,
        PreviousEvent = t2.cEventData1,
        t2.SeqNo
FROM    IVRHistory t1
        OUTER APPLY
        (   SELECT  TOP 1 t2.dEventTime, t2.SeqNo, t2.cEventData1
            FROM    IVRHistory t2
            WHERE   t1.InteractionKey = t2.InteractionKey
            AND     t1.dEventTime >= t2.dEventTime
            AND     t1.SeqNo > t2.SeqNo
            AND     t2.cEventData1 <> 'Attendant Disconnect'
            ORDER BY t2.dEventTime DESC, t2.SeqNo DESC
        ) t2
WHERE   t1.cEventData1 = 'Attendant Disconnect'

1 个答案:

答案 0 :(得分:1)

我会使用APPLY

来解决这个问题
SELECT  t1.InteractionKey,
        DisconnectTime = t1.dEventTime,
        PreviousEventTime = t2.dEventTime,
        PreviousEvent = t2.cEventData1,
        t2.SeqNo
FROM    T t1
        OUTER APPLY
        (   SELECT  TOP 2 t2.dEventTime, t2.SeqNo, t2.cEventData1
            FROM    T t2
            WHERE   t1.InteractionKey = t2.InteractionKey
            AND     t1.dEventTime > t2.dEventTime
            ORDER BY t2.dEventTime DESC
        ) t2
WHERE   t1.cEventData1 = 'Disconnect';

这将在断开事件之前立即提供两条记录。如果重复次数需要两个以上的记录,则可以使用TOP 2 WITH TIES

如果没有您的样本输入和输出,我猜一点,但从您所说的最终聚合将是:

SELECT  t2.cEventData1,
        Occurances = COUNT(*)
FROM    T t1
        OUTER APPLY
        (   SELECT  TOP 2 t2.dEventTime, t2.SeqNo, t2.cEventData1
            FROM    T t2
            WHERE   t1.InteractionKey = t2.InteractionKey
            AND     t1.dEventTime > t2.dEventTime
            ORDER BY t2.dEventTime DESC
        ) t2
WHERE   t1.cEventData1 = 'Disconnect'
GROUP BY t2.cEventData1;