【问题标题】:SQL Server: use function after certain value in tableSQL Server:在表中某个值后使用函数
【发布时间】:2021-07-28 17:47:18
【问题描述】:

我试图找出存储的对话中两个特定点之间的时间差。这些观点在每次对话中都可能不同,这对我来说很困难。我需要代理的消息和它之后的第一个最终用户响应之间的时间差。

在下面 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 之间的时间差。

如图所示,Agent 和 EndUser 在每次对话中的顺序以及这些类型所处的位置可能不同。

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

【问题讨论】:

  • 数据图像确实不能帮助我们帮助您。花时间将您的数据发布为 DDL 和 DML 语句。另外不要忘记包括您在您的尝试之后的预期结果(并解释为什么它们没有工作)

标签: sql-server datediff


【解决方案1】:

看来您需要的逻辑是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

【讨论】:

    【解决方案2】:

    我认为这段代码应该对你有所帮助。

    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;
    

    【讨论】:

      猜你喜欢
      • 2011-08-27
      • 1970-01-01
      • 2016-02-29
      • 2010-10-31
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多