从DateTime列

时间:2018-01-18 22:07:14

标签: sql tsql datetime average

我正在计算从深夜运行的事件的平均开始时间,并且可能直到第二天早上才开始。

2018-01-09 00:01:38.000
2018-01-09 23:43:22.000

目前我所能生产的是平均11:52:30.0000000

我希望结果是~23:52

平均时间不会保持静态,因为此事件每天运行,我每天都会有新数据。我可能会采用最近的10条记录并对其进行平均。

4 个答案:

答案 0 :(得分:0)

让你运行SQL会很好,但可能你只需要正确格式化你的输出,它应该是这样的:

<div id="videoPlayer">
<video class="playerVideoElement" src="none_or_pathToContentVideo"></video>
<div id="adContainer">
<iframe id="adCreativeHTMLContent" class="overlaysVideoContent">
<html id="adCreativeDocument">
<video class="adVideoElement" src="pathToadVideo"></video>
<div>//.. creative interactive content</div>
</html>
</iframe>
</div>
</div>

答案 1 :(得分:0)

以下内容将计算datetime字段的平均值,并仅将结果作为24小时时间表示法返回。

SELECT CAST(CAST(AVG(CAST(<YourDateTimeField_Here> AS FLOAT)) AS DATETIME) AS TIME) [AvgTime] FROM <YourTableContaining_DateTime>

答案 2 :(得分:0)

以下将计算平均时间,无论是哪一天。

--SAMPLE DATA
create table #tmp_sec_dif
    (
        sample_date_time datetime
    )

insert into #tmp_sec_dif
values ('2018-01-09 00:01:38.000')
    , ('2018-01-09 23:43:22.000')

--ANSWER
declare @avg_sec_dif int

set @avg_sec_dif = 
    (select avg(a.sec_dif) as avg_sec_dif
    from (
        --put the value in terms of seconds away from 00:00:00
        --where 23:59:00 would be -60 and 00:01:00 would be 60
        select iif(
            datepart(hh, sample_date_time) < 12 --is it morning?
            , datediff(s, '00:00:00', cast(sample_date_time as time)) --if morning
            , datediff(s, '00:00:00', cast(sample_date_time as time)) - 86400 --if evening
            ) as sec_dif
        from #tmp_sec_dif
        ) as a
    )

select cast(dateadd(s, @avg_sec_dif, '00:00:00') as time) as avg_time_of_day

输出将是23:52:30.0000000

的答案

答案 3 :(得分:0)

此代码允许您定义日期分割点。例如18表示下午6点。时间计算将基于下午6点后的秒数。

-- Defines the hour of the day when a new day starts
DECLARE @DayDivision INT = 18

IF OBJECT_ID(N'tempdb..#StartTimes') IS NOT NULL DROP TABLE #StartTimes

CREATE TABLE #StartTimes(
    start DATETIME NOT NULL
)

INSERT INTO #StartTimes
VALUES 
     ('2018-01-09 00:01:38.000')
    ,('2018-01-09 23:43:22.000')

SELECT 
    -- 3. Add the number of seconds to a day starting at the 
    --    day division hour, then extract the time portion
    CAST(DATEADD(SECOND,
        -- 2. Average number of seconds
        AVG(
            -- 1. Get the number of seconds from the day division point (@DayDivision)
            DATEDIFF(SECOND, 
                CASE WHEN DATEPART(HOUR,start) < @DayDivision THEN
                    SMALLDATETIMEFROMPARTS(YEAR(DATEADD(DAY,-1,start)),MONTH(DATEADD(DAY,-1,start)),DAY(DATEADD(DAY,-1,start)),@DayDivision,0)
                ELSE
                    SMALLDATETIMEFROMPARTS(YEAR(start),MONTH(start),DAY(start),@DayDivision,0)
                END
            ,start)
        )
    ,'01 jan 1900 ' + CAST(@DayDivision AS VARCHAR(2)) + ':00') AS TIME) AS AverageStartTime
FROM #StartTimes