如何创建用于计算SQL Server数据库中的平均时间的存储过程

时间:2017-07-31 11:44:23

标签: sql-server

我有一张3000记录的表。 如果我运行select * from TableName

输出:

TestSequence    TestName  ExecutionSequence ExecutionSeconds
1                   xyz             1         1.63
1                   xyz             2         1.56
1                   xyz             3         1.55
1                   xyz             4         1.55
1                   xyz             5         1.66
15                  abc             1         0.84
15                  abc             2         0.84
15                  abc             3         0.84
15                  abc             4         0.84
15                  abc             5         0.84
16                  ttt             1         1.75
16                  ttt             2         1.45
16                  ttt             3         1.43
16                  ttt             4         1.48
16                  ttt             5         1.50
17                  www             1         5.22
17                  www             2         5.16
17                  www             3         5.22
17                  www             4         5.21
17                  www             5         5.20
18                  ccc             1         3.48
18                  ccc             2         3.47
18                  ccc             3         3.47
18                  ccc             4         3.47
18                  ccc             5         3.49

每个测试运行5次由ExecutionSequence列表示,所以我想要实现的是创建一个存储过程,为每个testName删除或省略最大和最小ExecutionSeconds,并计算剩余3的平均值。我是试图建立这个程序,但我被卡住了。

这是我的代码:

 USE [db1];  
 GO  
 CREATE PROCEDURE tests_CalculateAverageRunTime
 (  

     @TestSenquence varchar(50) = NULL
  )      
AS
BEGIN   
SET NOCOUNT ON

        SELECT  TestName, TestSequence, AVG(ExecutionSeconds) as AverageRunTime
        FROM TableName 
        WHERE (@TestSenquence IS NULL OR TestSequence = @TestSenquence)

        Group By TestName, TestSequence

SET NOCOUNT OFF
END
GO 

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER()标识具有最大值和最小值的行,然后将其过滤掉:

SELECT  TestName, TestSequence, AVG(ExecutionSeconds) as AverageRunTime
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY TestName, TestSequence ORDER BY ExecutionSeconds) as seqnum_a,
             ROW_NUMBER() OVER (PARTITION BY TestName, TestSequence ORDER BY ExecutionSeconds DESC) as seqnum_d
      FROM TableName t
      WHERE (@TestSenquence IS NULL OR TestSequence = @TestSenquence)
     ) t
WHERE seqnum_a > 1 AND seqnum_d > 1
Group By TestName, TestSequence;

如果是最大或最小的关系,则只删除一个。这与您平均三个值的愿望是一致的。