SQL服务器:在table中的特定值后使用函数

SQL Server: use function after certain value in table

我试图找出存储对话中两个特定点之间的时差。这些要点在每次谈话中可能会有所不同,这让我感到很困难。我需要 Agent 的消息和它之后的第一个 EndUser 响应之间的时间差。

在下面 CaseNr 1234 的示例中,我需要 MessageNrs 3&4、5&6 和 7&8 之间的时间差。 在 CaseNr 2345 中,我需要 MessageNrs 3&4、5&6、7&8 和 10&11 之间的时差。 在 CaseNr 4567 中,我需要 2&3 和 4&5 之间的时差。

如图所示,代理和最终用户在每次对话中的顺序以及这些类型所处的位置可能不同。

有没有办法按照我在 SQL 服务器中描述的方式计算时差?

我认为这段代码应该能帮到你。

with t(MessageNr,CaseNr,Type, AgentTime, EndUserTime) as
(
    select 
        t1.MessageNr,
        t1.CaseNr,
        t1.Type,
        t1.EntryTime,
        (select top 1 t2.EntryTime 
        from [Your_Table] as t2 
        where t1.CaseNr = t2.CaseNr
            and t2.[Type] = 'EndUser'
            and t1.EntryTime < t2.EntryTime
        order by t2.EntryTime) as userTime
    from [Your_Table] as t1
    where t1.[Type] = 'Agent'
)
select t.*, DATEDIFF(second, AgentTime, EndUserTime)
from t;

看来您需要的逻辑是 Agent 行与紧随其后的 EndUser 行之间的时间差。

您可以使用 LEAD 执行此操作,这将比使用自联接更高效。

SELECT *,
    DATEDIFF(second, t.EntryTime, t.NextTime) TimeDifference
FROM (
    SELECT *,
        LEAD(CASE WHEN t.[Type] = 'EndUser' THEN t.EntryTime END) NextTime
    FROM myTable t
) t
WHERE t.[Type] = 'Agent'
  AND t.NextTime IS NOT NULL