请考虑下表中的呼叫中心座席状态。 我需要的是计算在" 休息"" 休息"中花费的总和时间布莱恩一整天。
这是我尝试执行的内容,但它会返回一些不准确的值:
select sum (CASE
WHEN State = 'Not Working' and Reason = 'Break'
THEN Datediff(SECOND, [Time_Stamp], CURRENT_TIMESTAMP)
else '' END) as Break_Overall
from MyTable
where Agent = 'Bryan'
答案 0 :(得分:1)
使用lead()
:
select agent,
sum(datediff(second, timestamp, next_timestamp)
from (select t.*,
lead(timestamp) over (partition by agent order by time_stamp) as next_timestamp
from mytable t
) t
where state = 'Not Working' and reason = 'Break'
group by agent;
如果代理当前可以休息,您可能需要默认值:
select agent,
sum(datediff(second, timestamp, next_timestamp)
from (select t.*,
lead(timestamp, 1, current_timestamp) over (partition by agent
order by time_stamp) as next_timestamp
from mytable t
) t
where state = 'Not Working' and reason = 'Break'
group by agent;
我对这种逻辑感到有点不舒服,因为current_timestamp
有一个日期组件,但你的时间不是。
编辑:
在SQL Server 2008中,您可以执行以下操作:
select agent,
sum(datediff(second, timestamp, coalesce(next_timestamp, current_timestamp))
from (select t.*, t2.timestamp as next_timestamp
from mytable t outer apply
(select top 1 t2.*
from mytable t2
where t2.agent = t.agent and t2.time_stamp > t.time_stamp
order by t.time_stamp
) t2
) t
where state = 'Not Working' and reason = 'Break'
group by agent;
答案 1 :(得分:0)
实际上,您可以获得记录的Time_Stamp和CURRENT_TIMESTAMP之间的区别。这可能不正确 - 你可能希望得到记录的Time_Stamp和 next Time_Stamp之间相同的" Agent"。
(注意&#34;如果您有多个具有相同名称的代理,代理&#34;也会出现问题;您可能希望将代理存储在不同的表中并使用唯一标识符作为外键。)< / p>
所以,对于布莱恩来说,你得到了
the sum of both the "total time" for the 8:30:21 record AND the 11:34:58 record
,这是对的 - 除了您正在计算&#34;总时间&#34;不正确,所以相反,你得到the sum of the time since 8:30:21 and 11:34:58
。