查找SQL中多行的平均时间(以秒为单位)

时间:2014-06-18 00:26:05

标签: sql datetime

我目前正在尝试查找多行的两个不同日期之间的平均值。因此,对于每个创建的日期,减去指定的日期。然后找到所有日期的平均值(在几秒钟内查找结果)

declare @offset int; 
declare @st_date date;
declare @en_date date;

set @offset = (@BrowserTimezoneOffSet);
set @st_date = (@st_datein);
set @en_date = (@en_datein);

select 
 avg(subtract) as [AVG Assigned Time]
 from
    (select
        DATEDIFF(ss, ign.createdDate, ign.assignDate) as subtract
        from
        (select
            DATEADD(mi,@offset,s.CreatedDateTime) as createdDate
            ,DATEADD(mi,@offset,w.AuditHistoryDateTime) as assignDate
        from ServiceReq s, Audit_ServiceReq w
        WHERE   
        w.OwnerTeam_IsChanged = N'True' --owner was actually changed at some point
        AND s.Subject = N'General Request'
        AND w.AuditHistoryUser != N'InternalServices' --Doesn't include those done automagically by system
        AND w.AuditHistoryEventType != 1 --Doesn't include creation
        AND DATEADD(mi,@offset,s.CreatedDateTime) >= @st_date --greater than start date
        AND DATEADD(mi,@offset,s.CreatedDateTime) <= @en_date --less than end date
        AND s.CreatedByTeam in ('IT Helpdesk','Unassigned') --check the team
        ) as ign enter code here
    ) as dp 

上面没有返回准确的数据我在这方面很新,我不确定我做错了什么。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

虽然你可能能够做到这一点,但它可能不是接近它的最好方法。

我要么检索行并在代码中进行计算(如果它保证是相对较少的行数),或者编写一个使用游标检索行的存储过程并迭代它们计算你想要的。

这两种方法都比可读性更强,因此比极其复杂的SQL查询更易于维护。

我希望它的表现也会更好。多年来,我一直看到基于游标的计算访问的简单选择优于复杂的选择语句。