在DateTime SQL中根据小时获取平均值时遇到问题

时间:2016-12-06 18:58:23

标签: sql sql-server

我在查询工作时遇到了一些麻烦,我希望根据我的样本数据,我希望根据某天的TestDate小时得到平均经过的时间。所以例如,如果我周一下午1点的经过时间为12,周五下午1点的经过时间为16,我希望周一的平均经过时间为1,为12,周五为16,而不是下午1点经过的时间一般是14(请参阅下面的查询以获得更好的解释)。

以下是我正在使用的示例数据:

 TestDate                   ElapsedTime
2016-12-05 15:04:47.000     00:00:54.8507507
2016-12-05 15:04:47.000     00:00:03.8507507
2016-12-05 11:04:47.000     00:00:14.8507507
2016-12-05 12:04:47.000     00:00:05.8507507
2016-12-05 13:04:47.000     00:00:07.8507507
2016-12-09 13:04:47.000     00:00:50.8507507
2016-12-05 13:04:47.000     00:00:04.8507507
2016-12-05 13:04:47.000     00:00:04.8507507
2016-12-05 13:04:47.000     00:00:04.8507507
2016-12-05 13:04:47.000     00:00:04.8507507
2016-12-07 13:04:47.000     00:00:04.8507507
2016-12-09 13:04:47.000     00:00:50.8507507

注意:TestDate是一个DateTime,而ElapsedTime是一个varchar(它保存为TimeSpan,然后转换为c#应用程序中的字符串)。

以下是我的查询,我可以获得平均经历时间,但我无法根据天数计算小时数,一般只需几小时:

  Select x.TestRunTime,
    Avg(x.ElapsedTime) As AverageElapsedTime
FROM 
(
    SELECT
    DATEPART(HOUR, CAST(TestDate AS TIME(6))) AS TestRunTime,
    (DatePart(minute,Cast(ElapsedTime as Time(6))) * 60) +
        DatePart(second,Cast(ElapsedTime as Time(6))) + 
        (DatePart(millisecond,Cast(ElapsedTime as Time(6))) * .001) 
        As ElapsedTime
        FROM RunTimes
) AS x
GROUP BY x.TestRunTime

任何人都可以帮我弄清楚我错过了什么吗?我知道我很接近,我只是无法获得经过时间的日期部分。

谢谢,

2 个答案:

答案 0 :(得分:0)

再添加一个datepart。并使用DATEDIFF获得ms分数的秒数。

Select x.TestRunTime,
       x.DayOfWeek,     
       Avg(x.ElapsedTime) As AverageElapsedTime
FROM 
(
    SELECT
    DATEPART(HOUR, TestDate) AS TestRunTime, 
    DATEPART(dw, TestDate) AS DayOfWeek,
    DATEDIFF(ms, 0, Cast(ElapsedTime as Time(6)))/1000. as  ElapsedTime
        FROM RunTimes
) AS x
GROUP BY x.TestRunTime, x.DayOfWeek

修改

如果你每小时需要平均值

Select x.TestRunTime,   
       Avg(x.ElapsedTime) As AverageElapsedTime
FROM 
(
    SELECT
    DATEADD(hh,DATEDIFF(hh,0,TestDate),0) AS TestRunTime, 
    DATEDIFF(ms, 0, Cast(ElapsedTime as Time(6)))/1000. as  ElapsedTime
        FROM RunTimes
) AS x
GROUP BY x.TestRunTime

答案 1 :(得分:0)

我使用格式化功能。

这是我用它做的代码:

Select x.TestRunTime,
    Avg(x.ElapsedTime) As AverageElapsedTime
FROM 
(
    SELECT
        Format(TestDate, 'MMMM dd, HH') AS TestRunTime, 
    DATEPART(dw, TestDate) AS DayOfWeek,
    (DatePart(minute,Cast(ElapsedTime as Time(7)))) +
    DatePart(second,Cast(ElapsedTime as Time(7))) + 
    (DatePart(millisecond,Cast(ElapsedTime as Time(7))) * .0001) 
    As ElapsedTime
    FROM RunTimes
) AS x
GROUP BY x.TestRunTime, x.DayOfWeek