Adding time values that equal more than 24 hours - sql

I'm trying to sum up some time values, and when my sum exceeds 24 hours it subtracts 24 from the total.
Here's my SQL:
SELECT
UserID,
First_NM,
Last_NM,
MgrName,
CONVERT(varchar(5), DATEADD(minute, SUM(OnProd)/60, 0), 114) as OnProd,
CONVERT(varchar(5), DATEADD(minute, SUM(OffProd)/60, 0), 114) as OffProd,
CONVERT(varchar(5), DATEADD(minute, SUM(OnProd+OffProd)/60, 0), 114) as SumProd
FROM (
SELECT
UserID,
First_NM,
Last_NM,
MgrName,
CASE WHEN WorkUnitType LIKE '%On%' THEN DATEDIFF(s, DateStart, DateEnd) ELSE 0 END AS OnProd,
CASE WHEN WorkUnitType LIKE '%Off%' THEN DATEDIFF(s, DateStart, DateEnd) ELSE 0 END AS OffProd
FROM dbo.vw_mos_DPL_Reporting
) a
Group By
UserID,
First_NM,
Last_NM,
MgrName
And here's my current output:
UserID First_NM Last_NM OnProd OffProd SumProd
A05878 STEVEN LANTE 22:28 09:55 08:23
ARGLIN ARNIE FREEL 00:00 00:00 00:00
B96695 JENNIFER LARK 21:32 18:49 16:21
PATYOI PATTY TROTTER 04:29 00:03 04:32
How would I go about fixing this? Just to be clear, I want to show something like 38:24 or whatever the actual sum is. Total hours:Total minutes/60

It's a little inelegant, but you might try calculating the minutes and the hours separately and concatenating, eg, instead of
CONVERT(varchar(5), DATEADD(minute, SUM(OnProd)/60, 0), 114) as OnProd
try
SELECT CAST(SUM(OnProd)/3600 AS VARCHAR(6)) + ':' + RIGHT('00' + CAST((SUM(OnProd) % 3600) / 60 AS VARCHAR(6)),2) AS OnProd
You have to do the same thing for OffProd and SumProd as well.

Related

Query Datediff to output HH:MM in SQL Server

I'm working with SQL Server 2012, and I have two columns start and end with varchar(5) values in HH:MM format.
The data looks like this
ID Start End
------------------------
1 00:00 06:00
2 06:00 16:00
3 16:00 18:00
4 18:00 24:00
My query is like this:
SELECT
a.start,
a.[end],
RIGHT('0' + CONVERT(VARCHAR(3), DATEDIFF(MINUTE, a.Start, a.[end]) / 60), 2) + ':' +
RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(MINUTE, a.Start, a.[end]) % 60), 2) AS TotalHours
FROM
TransactionActivity a
I exec the query with where clause based on ID number, it gives me the correct result, until in ID 4: i got error like this
Conversion failed when converting date and/or time from character string.
I think it because the End time value is 24:00, how can I make it to get the time difference?
I think you'd be better off converting them into full datetime's (using an arbitrary date) because then the date functions will work correctly.
select
a.[start]
, a.[end]
, RIGHT('0' + CONVERT(varchar(3),DATEDIFF(minute,a.[Start], a.[end])/60),2) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,a.[Start],a.[end])%60),2)
as TotalHours
from (
select id
, case when [Start] = '24:00' then dateadd(minute, 1, convert(datetime, '23:59')) else convert(datetime, [Start]) end [Start]
, case when [End] = '24:00' then dateadd(minute, 1, convert(datetime, '23:59')) else convert(datetime, [End]) end [End]
from TransactionActivity
) a

how to check difference in time

following code returns
CREATE TABLE #emp1
(
empid VARCHAR(50),
empname VARCHAR(50),
intime SMALLDATETIME,
outtime SMALLDATETIME
)
INSERT INTO #emp1
VALUES (2500,
'Arun',
'2014-01-01 09:00:00',
'2014-01-01 10:30:0'),
(2500,
'Arun',
'2014-01-01 11:00:00:00',
'2014-01-01 11:00:0'),
(2500,
'Arun',
'2014-01-01 11:30:00:00',
'2014-01-01 19:00:00')
SELECT empid,
Cast(intime AS DATE)
AS workingday,
empname,
RIGHT('0' + CONVERT(VARCHAR, Floor(Sum( Datediff( mi, intime, outtime)/
60.0))),
2)
+ ':'
+ RIGHT('0' + CONVERT(VARCHAR, Sum( Datediff( mi, intime, outtime))%60),
2) AS
[total work_hour(s)],
CONVERT(VARCHAR(5), Max(outtime) - Min(intime), 108)
AS Difference,
Cast(Dateadd(minute, Sum(Datediff(mi, intime, outtime)) - 45, 0) AS TIME)
AS
TotalTime,
Cast(Dateadd(minute, CASE
WHEN Sum(Datediff(mi, intime, outtime)) > 525 THEN
Sum(
Datediff(mi, intime, outtime)) - 525
ELSE 0
END, 0) AS TIME)
AS OverTime
FROM #emp1
GROUP BY empid,
empname,
Cast(intime AS DATE)
DROP TABLE #emp1
as
EmpId workingday EmpName total work_hour(s) Difference TotalTime OverTime
2500 2014-01-01 Arun 09:00 10:00 08:15:00.0000000 00:15:00.0000000
Here TotalTime is 08:15 and OverTime is 00:15. Everything is fine.
However, I need another field ActualTime
i.e. if TotalTime is greater than 8 hours then ActualTime is the difference of TotalTime and OverTime. In this example ActualTime should be 08:00.
If TotalTime is less than 8 hours then ActualTime is the same as TotalTime.
Finally, I also want to avoid excess zeros in TotalTime and OverTime
I imagine you want something like this: *EDIT nullcheck added
;with x as
(
SELECT empid,
Cast(intime AS DATE) workingday,
empname,
cast(dateadd(mi, sum(datediff(mi, 0, outtime - intime)), 0) as time) twh,
cast(dateadd(mi,datediff(mi,0,max(outtime)-min(intime)), 0) as time) Difference,
case when count(outtime)=count(*) then '' end nullcheck
FROM #emp1
GROUP BY empid, empname, Cast(intime AS DATE)
)
select empid, workingday, empname,
nullcheck+left(twh, 5) [total_hours],
nullcheck+left(Difference, 5) Difference,
nullcheck+left(cast(dateadd(mi, -45, twh)as time ),5) TotalTime,
nullcheck+left(case when twh > '08:45' then cast(dateadd(mi, -525, twh) as time) else '00:00' end, 5) OverTime,
nullcheck+left(case when twh > '08:00' then '08:00' else twh end, 5) actualtime
from x
Result:
empid workingday empname total_hours Difference TotalTime OverTime actualtime
2500 2014-01-01 Arun 09:00 10:00 08:15 00:15 08:00
First I'd wrap your entire current query in a Common Table Expression, so that the parts of it can be reused.
WITH CalculatedTime AS (SELECT empid,
Cast(intime AS DATE) AS workingday,
empname,
RIGHT('0' + CONVERT(VARCHAR, Floor(Sum( Datediff( mi, intime, outtime)/
60.0))),
2)
+ ':'
+ RIGHT('0' + CONVERT(VARCHAR, Sum( Datediff( mi, intime, outtime))%60),
2) AS [total work_hour(s)],
CONVERT(VARCHAR(5), Max(outtime) - Min(intime), 108)
AS Difference,
Cast(Dateadd(minute, Sum(Datediff(mi, intime, outtime)) - 45, 0) AS TIME)
TotalTime,
Cast(Dateadd(minute, CASE
WHEN Sum(Datediff(mi, intime, outtime)) > 525 THEN
Sum(
Datediff(mi, intime, outtime)) - 525
ELSE 0
END, 0) AS TIME)
OverTime
FROM #emp1
GROUP BY empid,
empname,
Cast(intime AS DATE) )
Now we can refer to CalculatedTime as a table in itself, and we don't need to repeat any of that nasty logic used for calculating the TotalTime column.
So the final step is to use a case statement to perform the calculation you are after:
SELECT *,
CASE WHEN DATEDIFF(minute,TotalTime,'08:00') > 0 THEN TotalTime
ELSE DATEADD(minute, DATEDIFF(minute,OverTime, 0), TotalTime)
END AS ActualTime
FROM CalculatedTime
The formatting part of the problem (remove the extra zeros) is a separate question that has been answered many times before on StackOverflow.

DATEDIFF in HH:MM:SS format

I need to calculate the total length in terms of Hours, Minutes, Seconds, and the average length, given some data with start time and end time.
For example the result must be something like 45:15:10 which means 45 hours 15 min 10 sec, or 30:07 for 30 min 07 sec.
We're using SQL Server 2008 R2 and the conversion failed when time is more than 24:59:59. Any idea of how I could do this?
For information, the columns in the table are Id, StartDateTime, EndDateTime, etc. I need to make a monthly report which contains the recordings count of the month, the total length of these records, and the average length. I'd like to know if there is an easy way to perform all of this.
You shouldn't be converting to time - it is meant to store a point in time on a single 24h clock, not a duration or interval (even one that is constrained on its own to < 24 hours, which clearly your data is not). Instead you can take the datediff in the smallest interval required (in your case, seconds), and then perform some math and string manipulation to present it in the output format you need (it might also be preferable to return the seconds to the application or report tool and have it do this work).
DECLARE #d TABLE
(
id INT IDENTITY(1,1),
StartDateTime DATETIME,
EndDateTime DATETIME
);
INSERT #d(StartDateTime, EndDateTime) VALUES
(DATEADD(DAY, -2, GETDATE()), DATEADD(MINUTE, 15, GETDATE())),
(GETDATE() , DATEADD(MINUTE, 22, GETDATE())),
(DATEADD(DAY, -1, GETDATE()), DATEADD(MINUTE, 5, GETDATE())),
(DATEADD(DAY, -4, GETDATE()), DATEADD(SECOND, 14, GETDATE()));
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
FROM #d
)
SELECT id, StartDateTime, EndDateTime,
[delta_HH:MM:SS] = CONVERT(VARCHAR(5), d/60/60)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
[avg_HH:MM:SS] = CONVERT(VARCHAR(5), a/60/60)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;
Results:
id StartDateTime EndDateTime delta_HH:MM:SS avg_HH:MM:SS
-- ------------------- ------------------- -------------- ------------
1 2013-01-19 14:24:46 2013-01-21 14:39:46 48:15:00 42:10:33
2 2013-01-21 14:24:46 2013-01-21 14:46:46 0:22:00 42:10:33
3 2013-01-20 14:24:46 2013-01-21 14:29:46 24:05:00 42:10:33
4 2013-01-17 14:24:46 2013-01-21 14:25:00 96:00:14 42:10:33
This isn't precisely what you asked for, as it won't show just MM:SS for deltas < 1 hour. You can adjust that with a simple CASE expression:
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
FROM #d
)
SELECT id, StartDateTime, EndDateTime,
[delta_HH:MM:SS] = CASE WHEN d >= 3600 THEN
CONVERT(VARCHAR(5), d/60/60) + ':' ELSE '' END
+ RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
[avg_HH:MM:SS] = CASE WHEN a >= 3600 THEN
CONVERT(VARCHAR(5), a/60/60) + ':' ELSE '' END
+ RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;
This query changes the delta column in the 2nd row in the above result from 0:22:00 to 22:00.
I slightly modified Avinash's answer as it may end with error if difference is too big. If you need only HH:mm:ss it is sufficient to distinguish at seconds level ony like this:
SELECT CONVERT(time,
DATEADD(s,
DATEDIFF(s,
'2018-01-07 09:53:00',
'2018-01-07 11:53:01'),
CAST('1900-01-01 00:00:00.0000000' as datetime2)
)
)
SELECT CONVERT(time,
DATEADD(mcs,
DATEDIFF(mcs,
'2007-05-07 09:53:00.0273335',
'2007-05-07 09:53:01.0376635'),
CAST('1900-01-01 00:00:00.0000000' as datetime2)
)
)
If you want to do averages, then the best approach is to convert to seconds or fractions of a day. Day fractions are convenient in SQL Server, because you can do things like:
select avg(cast(endtime - starttime) as float)
from t
You can convert it back to a datetime using the reverse cast:
select cast(avg(cast(endtime - starttime as float) as datetime)
from t
The arithmetic to get the times in the format you want . . . that is a pain. You might consider including days in the final format, and using:
select right(convert(varchar(255), <val>, 120), 10)
To get the hours exceeding 24, here is another approach:
select cast(floor(cast(<val> as float)*24) as varchar(255))+right(convert(varchar(255), <val>, 120), 6)
It uses convert for minutes and seconds, which should be padded with 0s on the left. It then appends the hours as a separate value.
Starting in SQL SERVER 2012, you don't need to use DATEDIFF function. You can use FORMAT function to achieve what you want:
SELECT
FORMAT(CONVERT(TIME, [appoitment].[Start] - [appointment].[End]), N'hh\:mm') AS 'Duration'
FROM
[tblAppointment] (NOLOCK)
A way that avoids overflows and can include days and go all the way to milliseconds in the output:
DECLARE #startDate AS DATETIME = '2018-06-01 14:20:02.100'
DECLARE #endDate AS DATETIME = '2018-06-02 15:23:09.000'
SELECT CAST(DATEDIFF(day,'1900-01-01', #endDate - #startDate) AS VARCHAR) + 'd ' + CONVERT(varchar(22), #endDate - #startDate, 114)
The above will return
1d 01:03:06:900
And, off course, you can use the formatting of your choice
SQL Supports datetime substraction which outputs a new datetime relative to the MIN date (for instance 1900-01-01, you can probably get this value from some system variable) This works better than DATEDIFF, because DATEDIFF will count ONE for each "datepart boundaries crossed", even if the elapsed time is less than a whole datapart. Another nice thing about this method is that it allows you to use the date formatting conversions.
If days is the (positive) number of days, like 0.5 for 12 hours, use this expression to format it as a proper duration:
CONVERT(varchar(9), FLOOR(days * 24)) + RIGHT(CONVERT(char(19), CAST(days AS datetime), 120), 6)
Excel will understands values up to 9999:59:59 when pasted. There apply a custom format: [h]:mm:ss in the English version ([u]:mm:ss for Dutch).

SQL Server: hour and minute average

In SQL Server, I have a start time column on a table such as:
2011-09-18 08:06:36.000
2011-09-19 05:42:16.000
2011-09-20 08:02:26.000
2011-09-21 08:37:24.000
2011-09-22 08:22:20.000
2011-09-23 11:58:27.000
2011-09-24 09:00:48.000
2011-09-25 06:51:34.000
2011-09-26 06:09:05.000
2011-09-27 08:25:26.000
...
My question is, how can I get the average hour and minute? I want to know that what is the average start time for this job. (for example 07:22)
I tried something like this but didn't work:
select CAST(AVG(CAST(DATEPART(HH, START_TIME)AS float)) AS datetime) FROM
Thanks.
declare #T table(StartTime datetime)
insert into #T values
('2011-09-18 08:06:36.000'),
('2011-09-19 05:42:16.000'),
('2011-09-20 08:02:26.000'),
('2011-09-21 08:37:24.000'),
('2011-09-22 08:22:20.000'),
('2011-09-23 11:58:27.000'),
('2011-09-24 09:00:48.000'),
('2011-09-25 06:51:34.000'),
('2011-09-26 06:09:05.000'),
('2011-09-27 08:25:26.000')
;with C(Sec) as
(
select dateadd(second, avg(datediff(second, dateadd(day, datediff(day, 0, StartTime), 0), StartTime)), 0)
from #T
)
select convert(char(5), dateadd(minute, case when datepart(second, C.Sec) >= 30 then 1 else 0 end, C.Sec), 108)
from C
-----
08:08
Try this :
select CAST((SUM(DATEPART(HH, START_TIME) * 60 + DATEPART(MI, START_TIME))/COUNT(*))/60 AS VARCHAR(10)) + ':' + CAST((SUM(DATEPART(HH, START_TIME) * 60 + DATEPART(MI, START_TIME))/COUNT(*))%60 AS VARCHAR(10))
FROM.....

How to display roundof time

Using SQL Server 2005
Table1
ID Intime Outtime
001 00.21.00 00.48.00
002 08.23.00 13.45.00
003 00.34.00 00.18.00
I need to display the time time like 30 minutes or 1 Hours, it should display a roundoff time
Expected Output
ID Intime Outtime
001 00.30.00 01.00.00
002 08.30.00 14.00.00
003 01.00.00 00.30.00
How to make a query for the roundoff time.
You can round the current date to 30 minutes like:
select dateadd(mi, datediff(mi,0,getdate())/30*30, 0)
Explanation: this takes the number of minutes since the 0-date:
datediff(mi,0,getdate())
Then it rounds that to a multiple of 30 by dividing and multiplying by 30:
datediff(mi,0,getdate())/30*30
The result is added back to the 0-date to find the last 30 minute block
dateadd(mi, datediff(mi,0,getdate())/30*30, 0)
This can be adjusted easily for 60 minutes. :)
By checking the range
select ID,
DateAdd(mi, DateDiff(mi, 0, Intime +
case when InMi >= 15 then 30 - InMi else - InMi end), 0) as Intime,
DateAdd(mi, DateDiff(mi, 0, Outtime +
case when OutMi >= 15 then 30 - OutMi else - OutMi end), 0) as Outtime
FROM
(
select ID, Intime, Outtime,
datepart(mi, InTime) % 30 InMi,
datepart(mi, Outtime) % 30 OutMi
from tbl
) X
or by using the classical trick equivalent to Int(x+0.5)..
select ID,
dateadd(mi, ((datediff(mi, 0, Intime)+15)/30)*30, 0) Intime,
dateadd(mi, ((datediff(mi, 0, Outtime)+15)/30)*30, 0) Outtime
from tbl
IF you want to ROUNDUP instead
(you have a value going from 00.34.00 to 01.00.00) Then you need this
select ID,
dateadd(mi, ((datediff(mi, 0, Intime)+29)/30)*30, 0) Intime,
dateadd(mi, ((datediff(mi, 0, Outtime)+29)/30)*30, 0) Outtime
from tbl
Take a look at the DATEDIFF, DATEADD and DATEPART. You should be able to do what you want with that.
http://msdn.microsoft.com/en-us/library/ms189794.aspx
http://msdn.microsoft.com/en-us/library/ms186819.aspx
http://msdn.microsoft.com/en-us/library/ms174420.aspx
Here is kind of a step-by-step routine. I'm sure you can do something shorter and even more efficient. It would also simplify a lot if you used a datetime data type instead of a string.
declare #T table (id char(3), intime char(8), outtime char(8))
insert into #T values ('001', '00.21.00', '00.48.00')
insert into #T values ('002', '08.23.00', '13.45.00')
insert into #T values ('003', '00.34.00', '00.18.00')
;with
cteTime(id, intime, outtime)
as
( -- Convert to datetime
select
id,
cast(replace(intime, '.', ':') as datetime),
cast(replace(outtime, '.', ':') as datetime)
from #T
),
cteMinute(id, intime, outtime)
as
( -- Get the minute part
select
id,
datepart(mi, intime),
datepart(mi, outtime)
from cteTime
),
cteMinuteDiff(id, intime, outtime)
as
( -- Calcualte the desired diff
select
id,
case when intime > 30 then (60 - intime) else (30 - intime) end,
case when outtime > 30 then (60 - outtime) else (30 - outtime) end
from cteMinute
),
cteRoundTime(id, intime, outtime)
as
( -- Get the rounded time
select
cteTime.id,
dateadd(mi, cteMinuteDiff.intime, cteTime.intime),
dateadd(mi, cteMinuteDiff.outtime, cteTime.outtime)
from cteMinuteDiff
inner join cteTime
on cteMinuteDiff.id = cteTime.id
),
cteRoundedTimeParts(id, inHour, inMinute, outHour, outMinute)
as
( -- Split the time into parts
select
id,
cast(datepart(hh, intime) as varchar(2)) as inHour,
cast(datepart(mi, intime) as varchar(2)) as inMinute,
cast(datepart(hh, outtime) as varchar(2)) as outHour,
cast(datepart(mi, outtime) as varchar(2)) as outMinute
from cteRoundTime
),
cteRoundedTime(id, intime, outtime)
as
( -- Build the time string representation
select
id,
right('00'+inHour, 2)+'.'+right('00'+inMinute, 2)+'.00',
right('00'+outHour, 2)+'.'+right('00'+outMinute, 2)+'.00'
from cteRoundedTimeParts
)
select *
from cteRoundedTime