我有一个包含这些列的表:
Id, Method, DateTime, time taken
实施例
1, Done, 2014-06-22 08:18:00.000, 2000
2, Not Done, 2014-06-23 04:15:00.000, 5000
3, Done, 2014-06-23 14:15:00.000, 6000
我希望将结果设置为" DONE方法在上午8点到下午15点之间的每15分钟间隔内所花费的平均时间"
请指导我如何继续这个,我不确定光标是否符合此要求。
答案 0 :(得分:0)
我不完全确定这是否是你想要的,但这里是代码:
CREATE TABLE #Test(
id int IDENTITY(1,1) PRIMARY KEY,
Method nvarchar(50),
[Datetime] datetime,
timeTaken Bigint
)
CREATE TABLE #Result(
[Between] datetime,
[And] datetime,
[Avg] bigint)
INSERT INTO #Test (Method,Datetime,timeTaken)
VALUES(
'Done', '2014-06-22 08:18:00.000', 2000),
('Not Done', '2014-06-23 04:15:00.000', 5000),
('Done', '2014-06-23 14:15:00.000', 6000)
DECLARE @MaxTime datetime,@StartTime datetime,@Next datetime
SELECT @MaxTime = MAX([datetime]),
@StartTime = MIN([datetime])
FROM #TEST
WHILE @StartTime <= @MaxTime
BEGIN
SET @Next = (SELECT Dateadd(MINUTE,15,@StartTime))
INSERT INTO #Result
SELECT @StartTime AS [Between], @Next AS [And],AVG(timeTaken) AS [AVG]
FROM #Test
WHERE [Datetime] Between @StartTime AND @Next
AND Method = 'Done'
SET @StartTime = @Next
END
SELECT * FROM #Result
DROP TABLE #Test
DROP TABLE #Result
您现在可以设置选择*从#result的位置,您可以在上午8点到下午3点之间说出 如果这是你想要的,请告诉我
艾蒂安
答案 1 :(得分:0)
您可以使用CTE生成季度列表。然后left join
查找每季度的运行时间。 group by
将允许您计算平均值。
在SQL Server 2012中,time
类型可用,您可以:
; with quarters as
(
select cast('08:00' as time) as time
union all
select dateadd(minute, 15, time)
from quarters
where time <= '14:30'
)
select q.time
, avg(rt.time_taken) as avg_time_taken
from quarters q
left join
RunTime rt
on q.time <= cast(rt.dt as time)
and cast(rt.dt as time) < dateadd(minute, 15, q.time)
and method = 'Done'
group by
q.time
对于SQL Server 2008R2和earler,您可以使用整数数学:
; with quarters as
(
select 8*60 as min
union all
select min + 15
from quarters
where min < 15*60
)
select q.min / 60 as hour
, q.min % 60 as minute
, avg(rt.time_taken) as avg_time_taken
from quarters q
left join
(
select datepart(minute, dt) +
60 * datepart(hour, dt) as min
, time_taken
from RunTime
where method = 'Done'
) rt
on q.min <= rt.min and rt.min < q.min + 15
group by
q.min;