在子选择中求和返回不正确的值

时间:2014-02-10 17:26:14

标签: mysql join sum subquery

我正在处理一个查询,该查询计算在特定班次类型的一段时间内(时钟输出时间戳 - 时间戳的时钟)内完成的交互,并且我在一个子选择中对小时数求和,因为没有办法加入表格。当我这样做时,它不计算正确的时间。好像是在计算该日期的所有时间而不考虑班次类型(在查询中,班次类型称为“日程”)。这是查询:

select a.sp_id, sum(s.ints_sent) as 'ints sent', 
(
select SEC_TO_TIME(SUM(UNIX_TIMESTAMP(t.out_time) - UNIX_TIMESTAMP (t.in_time))) 
from bi.support_sp_timeclocks t
join bi.support_agents_list sal
on t.agent_sp_id = sal.sp_id
where t.agent_sp_id = a.sp_id
) 
AS 'time clocked'
from bi.cc_agents_hourly_stats s
    join bi.support_agents_list a 
        on s.desk_id = a.desk_id
    where date_sent = '2014-01-04' 
and exists 
(
    select *
    from bi.support_sp_timeclocks t2
    join bi.support_sp_shifts_scheduled ss 
    on t2.shift_id = ss.pk_id
    join bi.support_agents_list sal 
    on sal.sp_id = ss.agent_sp_id
    where sal.desk_id = a.desk_id
    and timestamp(s.date_sent, maketime(s.hour_sent,00,00)) >= t2.in_time and    
    timestamp(s.date_sent, maketime(s.hour_sent,00,00)) < t2.out_time
    and  schedule = 'SMS'
)
group by date_sent, a.public_name

它返回:

Agent ID  Interactions      time clocked
750705    16                420:47:21
418736    4             838:59:59

我知道对于第一个代理,'Time clocked'列应为.82小时(结果将采用时间戳格式)和第二个代理,结果应为.32小时。

有关为何发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:0)

838:59:59SEC_TO_TIME()输入溢出的明显标志。

让我们来看看你的子查询。您有此聚合查询(它使用SUM()),但没有任何GROUP BY

select SEC_TO_TIME(SUM(UNIX_TIMESTAMP(t.out_time) - UNIX_TIMESTAMP (t.in_time))) 
  from bi.support_sp_timeclocks t
  join bi.support_agents_list sal on t.agent_sp_id = sal.sp_id
 where t.agent_sp_id = a.sp_id

您似乎计算了自数据库开始以来代理记录的整个时间。如果这就是你想要的,那就不清楚为什么了。

如果你自己运行这个子查询,你会得到什么? (您不需要join操作。)

select  t.agent_sp_id,
        SEC_TO_TIME(SUM(UNIX_TIMESTAMP(t.out_time) 
                 - UNIX_TIMESTAMP (t.in_time)))   AS time_clocked
  from bi.support_sp_timeclocks t
 group by t.agent_sp_id

它能为您提供在您的应用程序中更有意义的东西吗? (我对此表示怀疑。)

尝试这个会更有意义吗?

select  t.agent_sp_id,
        DATE(t.out_time) AS day,
        SEC_TO_TIME(SUM(UNIX_TIMESTAMP(t.out_time) 
                 - UNIX_TIMESTAMP (t.in_time)))   AS time_clocked
  from bi.support_sp_timeclocks t
 group by t.agent_sp_id, DATE(t.out_time)

这将为您提供每个代理商每天花费的时间。

如果您想将查询限制在特定日期,可以尝试此操作。

select  t.agent_sp_id,
        DATE(t.out_time) AS day,
        SEC_TO_TIME(SUM(UNIX_TIMESTAMP(t.out_time) 
                 - UNIX_TIMESTAMP (t.in_time)))   AS time_clocked
  from bi.support_sp_timeclocks t
 where t.out_time >= '2014-01-04'
   and t.out_time <  '2014-01-04' + INTERVAL 1 DAY
 group by t.agent_sp_id, DATE(t.out_time)

一旦调试了计算花费时间的子查询,就可以将其加入到其他表中以获取报告结果集。

我希望这会有所帮助。