gpt4 book ai didi

sql - 将表格分组为 15 分钟间隔

转载 作者:行者123 更新时间:2023-12-02 23:05:15 28 4
gpt4 key购买 nike

T-SQL、SQL Server 2008 及更高版本

给定一个示例表

 StatusSetDateTime   | UserID | Status    | StatusEndDateTime   | StatusDuration(in seconds)
============================================================================
2012-01-01 12:00:00 | myID | Available | 2012-01-01 13:00:00 | 3600

我需要将其分解为使用 15 分钟间隔的 View ,例如:

IntervalStart       | UserID | Status | Duration

===========================================

2012-01-01 12:00:00 | myID | Available | 900

2012-01-01 12:15:00 | myID | Available | 900

2012-01-01 12:30:00 | myID | Available | 900

2012-01-01 12:45:00 | myID | Available | 900

2012-01-01 13:00:00 | myID | Available | 0

etc....

现在我已经能够四处搜索并找到一些会崩溃的查询我发现了类似的 MySql Here :

以及 T-SQL 的一些东西 Here

但在第二个示例中,他们正在对结果求和,而我需要将总持续时间除以用户按状态的间隔时间(900 秒)。

我能够调整第二个链接中的示例,将所有内容拆分为间隔,但返回了总持续时间,并且我无法完全弄清楚如何获得要拆分的间隔持续时间(并且仍然总计为原始总持续时间) )。

提前感谢您提供任何见解!

编辑:第一次尝试

 ;with cte as 
(select MIN(StatusDateTime) as MinDate
, MAX(StatusDateTime) as MaxDate
, convert(varchar(14),StatusDateTime, 120) as StartDate
, DATEPART(minute, StatusDateTime) /15 as GroupID
, UserID
, StatusKey
, avg(StateDuration) as AvgAmount
from AgentActivityLog
group by convert(varchar(14),StatusDateTime, 120)
, DATEPART(minute, StatusDateTime) /15
, Userid,StatusKey)

select dateadd(minute, 15*GroupID, CONVERT(datetime,StartDate+'00'))
as [Start Date]
, UserID, StatusKey, AvgAmount as [Average Amount]
from cte

编辑:第二次尝试

;With cte As
(Select DateAdd(minute
, 15 * (DateDiff(minute, '20000101', StatusDateTime) / 15)
, '20000101') As StatusDateTime
, userid, statuskey, StateDuration
From AgentActivityLog)

Select StatusDateTime, userid,statuskey,Avg(StateDuration)
From cte
Group By StatusDateTime,userid,statuskey;

最佳答案

;with cte_max as 
(
select dateadd(mi, -15, max(StatusEndDateTime)) as EndTime, min(StatusSetDateTime) as StartTime
from AgentActivityLog
), times as
(
select StartTime as Time from cte_max
union all
select dateadd(mi, 15, c.Time)
from times as c
cross join cte_max as cm
where c.Time <= cm.EndTime
)
select
t.Time, A.UserID, A.Status,
case
when t.Time = A.StatusEndDateTime then 0
else A.StatusDuration / (count(*) over (partition by A.StatusSetDateTime, A.UserID, A.Status) - 1)
end as Duration
from AgentActivityLog as A
left outer join times as t on t.Time >= A.StatusSetDateTime and t.Time <= A.StatusEndDateTime

sql fiddle demo

关于sql - 将表格分组为 15 分钟间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13648693/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com