代码之家  ›  专栏  ›  技术社区  ›  blackpass

mysql更新并设置当前行最后8小时的和值

  •  1
  • blackpass  · 技术社区  · 8 年前

    您好,我想计算8小时前当前数据的chat\u持续时间之和

    我有:
    agent 文本
    start_time 日期时间
    end_time 日期时间
    chat_duration bigint公司

    我需要将计算结果插入 past8_hours_chat_duration
    所以当我有:

    +----+--------+------------+----------+---------------+---------------------------+
    | id | agent  | start_time | end_time | chat_duration | past8_hours_chat_duration |
    +----+--------+------------+----------+---------------+---------------------------+
    |  1 | agent1 |   00.00.00 | 00.01.00 |            60 |                           |
    |  2 | agent2 |   00.00.00 | 00.01.00 |            60 |                           |
    |  3 | agent1 |   00.02.00 | 00.04.00 |           120 |                           |
    |  4 | agent1 |   08.02.00 | 08.03.00 |            60 |                           |
    +----+--------+------------+----------+---------------+---------------------------+
    
    

    我会尽可能多地解释。

    对于每一行,我需要找到当前代理过去8小时的持续时间之和 或者换言之:如果 start\u时间 在之后( currentData.start_time 8 hour )而不是其本身(当前行),也不是 start\u时间 在之后 当前数据。start\u时间

    对于id 1,没有针对的会话 agent1 其中 start\u时间 在之后 00.00.00 减去8小时(当前start\u时间),因此总计为0

    对于id 2,也没有针对的会话 agent2 其中 start\u时间 在之后 00.00.00 减去8小时(当前start\u时间),因此总计为0

    对于id 3,由于id 1的start\u时间为>00.02.00(当前)-8小时,总计60

    和 对于id 4,自 id 1为(<);08.02.00(当前)-8小时 &id 3大于;08.02.00(当前)-8小时 所以总数是120(从id 3开始)

    我正在使用mysql 首先,我使用:

    UPDATE chats AS c
    JOIN ( SELECT   agent, 
     SUM(chat_duration) AS sum_duration
     FROM     abc 
     GROUP BY agent
     ) AS c2
     ON c2.agent = c.agent 
    SET c.past8_hours_chat_duration = c2.sum_duration
    WHERE c.id < 10;
    

    但这是所有代理持续时间的总和,我应该如何找到过去8小时聊天数据的总和。

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Gordon Linoff    8 年前

    可以在使用相关子查询的查询中执行此操作:

    select c.*,
           (select sum(c2.duration)
            from chats c2
            where c2.agent = c.agent and
                  c2.start_time > c.start_time - interval 8 hour and
                  c2.start_time <= c.start_time
           ) as past8_hours_chat_duration
    from chats c;
    

    在MySQL中,将其集成到 update 这很棘手,因为您只能在 join 条款因此:

    update chats c join
           (select c.*,
                   (select sum(c2.duration)
                    from chats c2
                    where c2.agent = c.agent and
                          c2.start_time > c.start_time - interval 8 hour and
                          c2.start_time <= c.start_time
                   ) as past8_hours_chat_duration
            from chats c
           ) cc
           on c.id = cc.id
        c.past8_hours_chat_duration = coalesce(cc.past8_hours_chat_duration, 0);