【问题标题】:I'm looking to find an average difference between a series of 2 rows same column in SQL我正在寻找 SQL 中一系列 2 行同一列之间的平均差异
【发布时间】:2018-01-17 21:34:54
【问题描述】:

所以我查看了很多关于减法的问题以及所有关于 SQL 的问题,但没有找到完全相同的用途。

我正在使用一个表,并试图找出两个人在我的网站上交谈的平均响应时间。这是数据示例:

id      created_at          conversation_id sender_id   receiver_id
307165  2017-05-03 20:03:27 96557           24          1755
307166  2017-05-03 20:04:22 96557           1755        24
303130  2017-04-20 18:03:53 102458          2518        4475
302671  2017-04-18 20:11:20 102505          3100        1079
302670  2017-04-18 20:09:38 103014          3100        2676
350570  2017-09-18 20:59:56 103496          5453        929
290458  2017-02-16 13:38:47 103575          2841        2282
300001  2017-04-08 16:42:16 104159          2740        1689
304204  2017-04-24 17:31:25 104531          5963        1118
284873  2017-01-12 22:33:19 104712          3657        3967
284872  2017-01-12 22:31:38 104712          3967        3657

我想要的是根据 conversation_id 找到平均响应时间

【问题讨论】:

  • 请将您正在使用的数据库添加到问题标签并编辑您的问题以显示您期望的数据输出结果。另外,请说明您对查询的尝试以及它是如何不起作用的。

标签: sql row average


【解决方案1】:

嗯。 . .您可以通过获取两个对话者之间的下一行来获取给定行的“响应”。剩下的就是取平均值——这取决于数据库。

类似这样的:

select avg(next_created_at - created_at) -- exact syntax depends on the database
from (select m.*,
             (select min(m2.created_at)
              from messages m2
              where m2.sender_id = m.receiver_id and m.sender_id = m2.receiver_id and
                    m2.conversation_id = m.conversation_id and
                    m2.created_at > m.created_at
             ) next_created_at
      from messages m
     ) mm
where next_created_at is not null;

【讨论】:

    【解决方案2】:

    CTE 会负责将对话的开始和结束放在同一行。 然后使用DATEDIFF 计算响应时间,并取平均值。 假设每个对话只有两个条目(忽略 1 个或超过 2 个的其他条目)。

    WITH X AS (
        SELECT conversation_id, MIN(created_at) AS convstart, MAX(created_at) AS convend
        FROM theTable
        GROUP BY conversation_id
        HAVING COUNT(*) = 2
    ) 
    SELECT AVG(DATEDIFF(second,convstart,convend)) AS AvgResponse
    FROM X
    

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 2013-07-12
      • 2021-09-29
      • 2017-11-14
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      相关资源
      最近更新 更多