简体   繁体   English

SQL:计算行之间差异的平均值

[英]SQL: Calculate average of difference between rows

I have a table like below我有一张如下表

session   stepId        starttime     
------   -----------    -----    
1        1              10:00        
1        1              10:10        
1        2              10:40        
1        3              10:50        
1        4              11:00

And what I am aiming to calculate is the average time between each step Id, if the stepID is the same , like the first two rows, the most recent one is used.我的目标是计算每个步骤 Id 之间的平均时间,如果 stepID 相同,如前两行,则使用最近的行。 For example, for the above query, the result should be ((10:40 - 10:10) + (10:50-10:40) + (11:00 - 10:50))/3.例如,对于上面的查询,结果应该是 ((10:40 - 10:10) + (10:50-10:40) + (11:00 - 10:50))/3。 I am using MySQL.我正在使用 MySQL。

SELECT 
    TIME(AVG(M.timediff))
FROM
    (SELECT 
        TIME(b.starttime - a.starttime) AS timediff
    FROM
        (SELECT 
        stepId, MAX(starttime) starttime
    FROM
        test.test
    GROUP BY stepId) a
    LEFT JOIN test.test b ON a.stepId = b.stepId - 1
    WHERE
        a.starttime IS NOT NULL
            AND b.starttime IS NOT NULL) AS M

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM