如何计算SQL间隔之间的平均时间?

时间:2011-09-08 16:50:56

标签: sql datetime reporting-services ssis average

我有一个SQL表,我需要计算每次交易后的平均时间:

数据如下:

Tran1 07/09/2011 09:09:07  - CUSTOMER1 
Tran2 07/09/2011 09:30:46  - CUSTOMER1 
Tran3 07/09/2011 11:27:01  - CUSTOMER2 
Tran4 07/09/2011 11:29:22  - CUSTOMER2 
Tran5 07/09/2011 13:23:48  - CUSTOMER1 
Tran6 08/09/2011 14:21:29  - CUSTOMER3 
Tran7 08/09/2011 14:25:23  - CUSTOMER3 
Tran8 10/09/2011 13:28:57  - CUSTOMER1 
Tran9 10/09/2011 13:30:21  - CUSTOMER1 
Tran10 10/09/2011 13:49:13 - CUSTOMER4

该表是交易表,有三列: -

  

ID = UniqueID,TimeStamp = DataTime,CustomerId = UniqueID

所以如果我传入参数DateTime ..就说'10 / 09/2011' 我试图实现的结果是..

日期:10/9/2011 AverageQueueTime:3mins2secs - for exmaple

3 个答案:

答案 0 :(得分:2)

使用这样的查询(未经测试)

select t.customerID, TIMESTAMPDIFF(SECOND, MIN(t.timestamp), MAX(t.timestamp) ) / (COUNT(DISTINCT(t.timestamp)) -1)  as AverageTime
from Transaction_Table T
group by T.customerID

会在几秒钟内给你结果。请查看this answer以获得更好的解释

答案 1 :(得分:0)

假设您的表名为“MyTable”(它是否真的命名为Transaction!?)并且您希望在几分钟内得到差异:

SELECT  CustomerID ,
        SUM(timeSinceLastTransaction) / COUNT(*)
FROM    ( SELECT    * ,
                    DATEDIFF(MINUTE,
                             ( SELECT TOP 1
                                        t2.DataTime
                               FROM     MyTable t2
                               WHERE    t2.DataTime < t1.DataTime
                                        AND t2.CustomerId = t1.CustomerId
                               ORDER BY t2.DataTime DESC
                             ),
                             t1.DataTime
                             ) AS timeSinceLastTransaction
          FROM      MyTable t1
        ) AS IndividualTimes

这是一个相关的子查询。

答案 2 :(得分:0)

iridio解决方案的修改版

a)查询SQL Server数据库版本 b)支持空值

select t.customerID,
       Case When COUNT(DISTINCT(t.timestamp)) < = 1 THEN 0
             ELSE DATEDIFF(SECOND,MIN(t.timestamp),MAX(t.timestamp))
                   /(COUNT(DISTINCT(t.timestamp)) -1)  as AverageTime
 from Transaction_Table T
 group by T.customerID

注意:数据应按时间戳排序,否则会出错。