计算序列的平均阶段

时间:2017-10-30 23:26:21

标签: sql sql-server-2016

我需要计算并报告每个阶段在序列中花费的平均时间。

更多细节......

我有一个StageTable和一个DataTable。 StageTable是主表,包含序列中的阶段名称(按顺序)

StageTable

Id Stage
== ======
1   Alpha
2   Bravo
3   Charlie
4   Delta
5   End

DataTable包含阶段的开始时间。有些实体称为"序列" (具有相同的相关性Id),每个包含四个阶段。

数据表

CorrelationId   StageName   StartTime
==============  =========   =========
abc             Alpha        1pm
abc             Bravo        1.03pm          --implies that Alpha == 3min
abc             Charlie      1.07pm          --Bravo == 4min 
abc             Delta        1.10pm          --Charlie == 3min
abc             End          1.13pm
bbc             Alpha        2pm
bbc             Bravo        2.13pm          --Alpha == 13min
bbc             Charlie      2.17pm
bbc             Delta        2.21pm
bbc             End          2.25pm

输出

StageName   DurationTotal(min)  DurationAvg(min)
=========   ==================  ================  
Alpha        16                  8
Bravo        8                   4

1 个答案:

答案 0 :(得分:1)

我认为您下次需要lead()才能获得:

select t.*,
       lead(starttime) over (partition by correlationid order by starttime) as next_starttime
from t;

然后你可以得到这样的平均值:

select stagename,
       sum(datediff(second, starttime, next_starttime) * 1.0) as sum_dur,
       avg(datediff(second, starttime, next_starttime) * 1.0) as avg_dur
from (select t.*,
             lead(starttime) over (partition by correlationid order by starttime) as next_starttime
      from t
     ) t
group by stagename;