I have this table in SQL Server:
UserId Date Start Time End Time
------------------------------------------------------------------------------------
20 2012-04-02 00:00:00.000 NULL 2012-04-02 09:17:57.000
20 2012-04-02 00:00:00.000 2012-04-02 09:17:57.000 2012-04-02 09:57:55.000
20 2012-04-02 00:00:00.000 2012-04-02 09:57:55.000 2012-04-02 10:04:58.000
20 2012-04-02 00:00:00.000 2012-04-02 10:04:58.000 2012-04-02 10:21:40.000
20 2012-04-02 00:00:00.000 2012-04-02 10:22:15.000 2012-04-02 10:22:20.000
20 2012-04-02 00:00:00.000 2012-04-02 10:22:56.000 2012-04-02 10:23:33.000
I want to find the difference between start time and end time and sum up the difference hours based on date
Output required is:
UserID Time_Duration
-----------------------
20 1:20:20 (this is example not actuals)
Can anyone help me write a SQL query..
I have tried with the below query,
select sum(sub1.TotalSeconds / 3600) as [Hours], sum((sub1.TotalSeconds % 3600) / 60)
as [Minutes],
sum((sub1.TotalSeconds % 3600) % 60) as [Seconds],sub1.Date
from
(
SELECT
sub.UserID,
sub.Date,
sum(datepart(hour, sub.end_time-sub.start_time) * 3600) + sum(datepart(minute, sub.end_time-sub.start_time) * 60) +
sum(datepart(second, sub.end_time-sub.start_time)) as TotalSeconds
from.......
) AS sub
group by sub.UserID,sub.Date,sub.start_time,sub.end_time)
as sub1 group by sub1.Date;
I get the following result
Hours Minutes Seconds Date
3 347 515 2012-04-02 00:00:00.000
But i want to add the minutes if greater then 60 it has to hours as 3+1 hr and so on. Can any 1 help me where Im making mistake
Hi take a look at this:
SQLFIDDLE
It is NOT the most efficient and I believe it’s ugly for a code. However put it across for you to see the steps. You may get an idea out of it. Mainly using arimethic operators to get the reusults. There are extra fields as I was using it mainly to show you the data flow. I am sure other approaches are much much efficient in terms of performance. You can try.
Query:
Resutls
Updated Query only with one nested query
Infact you may achieve this with one nested query. Apology as this whole answer is
MYSQLbased. So hopefully you may take the logic out to implement that usingSQL Serversyntax 🙂