Home Forums SQL Server 2008 SQL Server Newbies Calculating time between two times five an arithmetic overflow RE: Calculating time between two times five an arithmetic overflow

  • SQLTestUser (8/15/2016)


    From the two time periods on Logdatetime itself

    Sorry, but this doesn't make much sense.

    I will have to take a wild guess.

    For your purposes it would have been best if there was an action for LogOn and an action for LogOff. Then you could simply say, that the time used on your system was the time between those two log entries.

    But no such actions exist in your example data.

    So I'm assuming that you want to calculate the time betwen the first and last log entries per order and sum up that per user:

    WITH

    -- Find the first and last log entry per user/date/order...

    UserOrderDayLog AS (

    SELECT UserID, OrderId, CAST(DATEDIFF(d,0,LogDateTime) AS DATETIME) AS LogDate, MIN(LogDatetime) AS FirstLogDateTime, MAX(LogDatetime) AS LastLogDateTime

    FROM dbo.Tlog

    GROUP BY UserId, OrderId, CAST(DATEDIFF(d,0,LogDateTime) AS DATETIME)),

    -- Subtract the first log time from the last one...

    UserOrderDaylogSeconds AS (

    SELECT UserID, OrderId, LogDate, DATEDIFF(s,FirstLogDateTime,LastLogDateTime) AS EstimatedSystemTimeInSeconds

    FROM UserOrderDayLog),

    -- Sum the time intervals per user

    UserSystemTime AS (

    SELECT UserId, SUM(EstimatedSystemTimeInSeconds) AS EstimatedTotalSystemTimeInSeconds

    FROM UserOrderDayLogSeconds

    GROUP BY UserId)

    -- Show the user results as seconds and as minutes, listed in descending order based on used system time..

    SELECT UserId, EstimatedTotalSystemTimeInSeconds, FLOOR(EstimatedTotalSystemTimeInSeconds / 60) AS EstimatedTotalSystemTimeInMinutes

    FROM UserSystemTime

    ORDER BY EstimatedTotalSystemTimeInSeconds DESC

    There are of course the built-in assumption that a user never starts processing an order on one date and ends the processing on a different date (past midnight).

    Your example data show that the same orderid is used over several (all) of the logged dates. Because of that I included the date as a part of the grouping.

    I have not actually tested the above query (at all), so no guaranties that it will work as intended. But hopefully it will give you some ideas so that you can move forward yourself.