How can i sum all the overtime duration - sql

I can't figure out how to sum all the over time duration from the query.
I have to sum it using another query...
This is the query I made to get the over time duration and the other time duration...
Select empId, firstTimeIn, firstTimeOut, secondTimeIn, secondTimeOut, overTimeIn, overTimeOut, attendanceDate,
(RIGHT('0' + CAST(DATEDIFF(second, Convert (time, firstTimeIn), Convert (time, firstTimeOut) ) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, firstTimeIn), Convert (time, firstTimeOut) ) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, firstTimeIn), Convert (time, firstTimeOut) ) % 3600 % 60 AS VARCHAR(2)), 2) ) as FirstTime
,
(RIGHT('0' + CAST(DATEDIFF(second, Convert (time, secondTimeIn), Convert (time, secondTimeOut) ) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, secondTimeIn), Convert (time, secondTimeOut) ) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, secondTimeIn), Convert (time, secondTimeOut) ) % 3600 % 60 AS VARCHAR(2)), 2)) as SecondTime
,
(RIGHT('0' + CAST(DATEDIFF(second, Convert (time, overTimeIn), Convert (time, overTimeOut) ) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, overTimeIn), Convert (time, overTimeOut) ) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, overTimeIn), Convert (time, overTimeOut) ) % 3600 % 60 AS VARCHAR(2)), 2)) as OverTimeDuration
from tbl_EmployeeAttendance Where attendanceDate BETWEEN '2019-09-01' AND '2019-09-15' And empId = '41' AND
((RIGHT('0' + CAST(DATEDIFF(second, Convert (time, firstTimeIn), Convert (time, firstTimeOut) ) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, firstTimeIn), Convert (time, firstTimeOut) ) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, firstTimeIn), Convert (time, firstTimeOut) ) % 3600 % 60 AS VARCHAR(2)), 2) ) >= '04:00:00') AND
((RIGHT('0' + CAST(DATEDIFF(second, Convert (time, secondTimeIn), Convert (time, secondTimeOut) ) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, secondTimeIn), Convert (time, secondTimeOut) ) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(second, Convert (time, secondTimeIn), Convert (time, secondTimeOut) ) % 3600 % 60 AS VARCHAR(2)), 2)) >= '04:00:00')
Try this code to add the table and its value....
CREATE TABLE tbl_EmployeeAttendance (
empId int,
firstTimeIn time,
firstTimeOut time,
secondTimeIn time,
secondTimeOut time,
overTimeIn time,
overTimeOut time,
attendanceDate varchar(100)
)
Insert into tbl_EmployeeAttendance VALUES ('41','07:30:00','12:10:00','12:55:00','17:20:00','17:45:00','19:30:02','2019-09-02')
Insert into tbl_EmployeeAttendance VALUES ('41','07:24:00','12:12:00','12:55:00','17:20:00','','','2019-09-03')
Insert into tbl_EmployeeAttendance VALUES ('41','07:23:00','12:10:00','12:55:00','17:20:00','','','2019-09-04')
Insert into tbl_EmployeeAttendance VALUES ('41','07:30:00','12:10:00','12:55:00','17:20:00','','','2019-09-05')
Insert into tbl_EmployeeAttendance VALUES ('41','07:24:00','12:12:00','12:55:00','17:20:00','','','2019-09-06')
Insert into tbl_EmployeeAttendance VALUES ('41','07:05:00','12:09:00','12:55:00','17:20:00','17:45:00','19:30:02','2019-09-09')
Insert into tbl_EmployeeAttendance VALUES ('41','07:05:00','12:09:00','12:55:00','17:20:00','','','2019-09-10')
Insert into tbl_EmployeeAttendance VALUES ('41','07:05:00','12:09:00','12:55:00','17:20:00','','','2019-09-11')
Insert into tbl_EmployeeAttendance VALUES ('41','07:30:00','12:09:00','12:55:00','17:20:00','','','2019-09-12')
Insert into tbl_EmployeeAttendance VALUES ('41','07:30:00','12:10:00','12:55:00','17:20:00','17:45:00','19:30:02','2019-09-13')

Use DATEDIFF(interval,date1,date2) If you work with MSSQL
SELECT empId, convert(varchar(5),totalFirstTiomeInHoure/3600)+':'+convert(varchar(5),totalFirstTiomeInHoure%3600/60)+':'+convert(varchar(5),(totalFirstTiomeInHoure%60)) as FirstTime,
convert(varchar(5),totalSecondTiomeInHoure/3600)+':'+convert(varchar(5),totalSecondTiomeInHoure%3600/60)+':'+convert(varchar(5),(totalSecondTiomeInHoure%60)) as SecondTime,
convert(varchar(5),totalOverTiomeInHoure/3600)+':'+convert(varchar(5),totalOverTiomeInHoure%3600/60)+':'+convert(varchar(5),(totalOverTiomeInHoure%60)) as overTime
From ( SELECT empId,
Sum(Datediff(s,firstTimeIn,firstTimeOut)) as totalFirstTiomeInHoure,
Sum(Datediff(s,secondTimeIn,secondTimeOut)) as totalSecondTiomeInHoure,
Sum(Datediff(s,overTimeIn,overTimeOut )) as totalOverTiomeInHoure
FROM [dbo].[tbl_EmployeeAttendance]
WHERE attendanceDate BETWEEN '2019-09-01' AND '2019-09-15'
GROUP BY [empId]) as TempData

Related

Query to calculate sum of time with above 24 hours interval

I have time like 25:00:00, 10:00:00, 30:00:00 and I want to calculate the sum of the values from database. How can I do that the current query for calculating sum is
SQL query:
SELECT
CAST(FORMAT((SUM((DATEPART("ss", Total_Time) +
DATEPART("mi", Total_Time) * 60 +
DATEPART("hh", Total_Time) * 3600)) / 3600), '00') AS varchar(max)) + ':' + CAST(FORMAT((SUM((DATEPART("ss", Total_Time) + DATEPART("mi", Total_Time) * 60 + DATEPART("hh", Total_Time) * 3600)) % 3600 / 60), '00') as varchar(max)) + ':' +CAST(FORMAT((SUM((DATEPART("ss", Total_Time) + DATEPART("mi", Total_Time) * 60 + DATEPART("hh", Total_Time) * 3600)) % 3600 % 60), '00') as varchar(max)) as WorkingTimeSum
FROM
tasker_usr.TaskTime
but I get an error
Cannot convert from datetime to character string
You cannot fit your values into a time datatype. It stores only value less than 23:59:59.9999999. Hence you cannot use DATEPART or DATEDIFF directly. One way is to split your values(as seconds) and do the sum. Something like
WITH CTE_SUM
AS (
SELECT SUM(LEFT(column_name, 2) * 3600
+ SUBSTRING(column_name, 4, 2) * 60
+ SUBSTRING(column_name, 7, 2)) AS SUM_AS_SECONDS
FROM YOUR_TABLE
)
SELECT CAST(SUM_AS_SECONDS / 3600 AS VARCHAR) + ':'
+ CAST(SUM_AS_SECONDS % 3600 / 60 AS VARCHAR) + ':'
+ CAST(((SUM_AS_SECONDS % 3600) % 60) AS VARCHAR) AS WorkingTimeSum
FROM CTE_SUM
Please note that this will work upto 99:99:99.If you have time values that are more than that, then you have to split based on : instead of hardcoding values in LEFT/Substring
Are you looking something like this ?
Declare #Hours Table(Hrs VARCHAR(20))
Declare #Hour TINYINT, #Minute INT,#Second INT, #InSeconds BIGINT, #Cdate DATETIME
INSERT #Hours
SELECT '25:00:00' Union All
SELECT '10:00:00' Union All
SELECT '30:00:00'
select #Hour = sum(cast(Left(Hrs,CharIndex(':',Hrs,1)-1) as int)) from #Hours
select #Minute = sum(cast(Substring(Hrs,CharIndex(':',Hrs,1)+1,2)as int)) from #Hours
select #Second = sum(cast(Substring(Hrs,CharIndex(':',Hrs,1)+4,2)as int)) from #Hours
Set #InSeconds = #Second + (#Minute * 60) + (#Hour *60 *60)
Set #Cdate = dateadd(second,#InSeconds,0)
select datediff(day,'1900-01-01',#Cdate) [Day(s)],
Format(#Cdate,'hh') [Hour(s)],
Format(#Cdate,'mm') [Minute(s)],
Format(#Cdate,'ss') [Second(s)]
Day(s)
Hour(s)
Minute(s)
Second(s)
2
05
00
00
Assuming that your format is HH(n):MM:SS (that is, hours can have 1 or more digits), you can decompose the value and reconstruct it. This requires string functions. You can get the total seconds as:
select sum(left(total_time, charindex(':', total_time) - 1) * 60 * 60 +
left(right(total_time, 5), 2) * 60 +
right(total_time, 2)
) as total_secs
from tasker_usr.TaskTime;
Note: This does implicit conversion from the string values to integers, but that should be okay if your values are consistent.
You can convert back to string:
select concat(format(total_secs / (60 * 60), '00:'),
format( (total_secs / 60) % 60, '00:'),
format(total_secs % 60, '00')
) as time_format
from (select sum(left(total_time, charindex(':', total_time) - 1) * 60 * 60 +
left(right(total_time, 5), 2) * 60 +
right(total_time, 2)
) as total_secs
from tasker_usr.TaskTime
) t

SQL Server : conversion failed when converting date and/or time from character with string past 12pm

For the past few days my code has worked, but today it has the following error:
Conversion failed when converting date and/or time from character string
Here is my code:
DECLARE #run_time INT
DECLARE #run_duration INT
SET #run_time = '120609'
SET #run_duration = '2600'
SELECT
h.step_id,
CAST(j.[name] AS VARCHAR) as JobName,
h.step_name,
CAST(REPLACE(LEFT(CAST(case
when len(#run_time) = 1 then '00:00:0' + cast(#run_time as varchar)
when len(#run_time) = 2 then '00:00:' + cast(#run_time as varchar)
when len(#run_time) = 3 then '00:0' + cast(left(#run_time,1) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 4 then '00:' + cast(left(#run_time,2) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 5 then '0' + cast(left(#run_time,1) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2, 2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
when len(#run_time) = 6 then cast(left(#run_time,2) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2,2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
END AS TIME), 8), ':', '') AS INT) StartTime
I discovered the only time the error appears is when the run_time goes past 120000 (12pm), hence why I've never noticed it before because the agent jobs have ran at 3am. It shouldn't be an issue in the future, but just in case it is I would like a fix for this. I can't find an example anywhere that's similar to my code. Unfortunately casting the results like this is the only way I can get a graph in SSRS to work. (INT > VARCHAR > TIME > INT).
edit - here is a better example of my code using one of the proposed answers:
SELECT
h.step_id,
CAST(j.[name] AS VARCHAR) as JobName,
h.step_name,
CAST(stuff(stuff(right('0000000' + h.run_time, 6), 5, 0, ':'), 3, 0, ':') as time)
FROM
msdb.dbo.sysjobs j
INNER JOIN msdb.dbo.sysjobhistory h ON j.job_id = h.job_id
Thanks,
If you are trying to calculate the start time from a string in HHMMSS format, then this method seems much simpler to me:
select cast(stuff(stuff(right('0000000' + str, 6), 5, 0, ':'), 3, 0, ':') as time)
from (values ('120609'), ('0'), ('1001')) v(str)
In your case the problem is the string which you are trying to convert: "12:20:60"
The converstion to TIME type fails.
DECLARE #run_time INT
DECLARE #run_duration INT
SET #run_time = '120609'
SET #run_duration = '2600'
SELECT
-- h.step_id,
--CAST(j.[name] AS VARCHAR) as JobName,
-- h.step_name,
--CAST(REPLACE(LEFT(CAST(
case
when len(#run_time) = 1 then '00:00:0' + cast(#run_time as varchar)
when len(#run_time) = 2 then '00:00:' + cast(#run_time as varchar)
when len(#run_time) = 3 then '00:0' + cast(left(#run_time,1) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 4 then '00:' + cast(left(#run_time,2) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 5 then '0' + cast(left(#run_time,1) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2,2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
when len(#run_time) = 6 then cast(left(#run_time,2) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2,2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
END ,
SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
--AS TIME)
--,8), ':', '') AS INT) StartTime
Did you check this out?
How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?
The best solution should be the one proposed by Gordon
This works for me:
SELECT
h.step_id,
CAST(j.[name] AS VARCHAR) as JobName,
h.step_name,
-- CAST(stuff(stuff(right('0000000' + h.run_time, 6), 5, 0, ':'), 3, 0, ':') as time)
(h.run_time / 1000000) % 100 as hour,
(h.run_time / 10000) % 100 as minute,
(h.run_time / 100) % 100 as second,
(h.run_time % 100) * 10 as millisecond,
dateadd(hour, (h.run_time / 1000000) % 100, dateadd(minute, (h.run_time / 10000) % 100, dateadd(second, (h.run_time / 100) % 100, dateadd(millisecond, (h.run_time % 100) * 10, cast('00:00:00' as time(2))))))
FROM
msdb.dbo.sysjobs j
INNER JOIN msdb.dbo.sysjobhistory h ON j.job_id = h.job_id
Btw, the CAST drives to error for me, as well
In case you don't want to use the select statement:
DECLARE #run_time INT
DECLARE #time_result TIME
SET #run_time = '120609'
SET #time_result = dateadd(hour, (#run_time / 1000000) % 100, dateadd(minute, (#run_time / 10000) % 100, dateadd(second, (#run_time / 100) % 100, dateadd(millisecond, (#run_time % 100) * 10, cast('00:00:00' as time(2))))))
select #time_result

SUM time in varchar/nvarchar data type field

I have troubles to SUM time in a varchar/nvarchar data type field.
This is the format what I'm trying to SUM: (HH:mm:ss)
Here you go:
create table tblTime (dt datetime)
insert tblTime values
('00:25:00'),
('00:20:00')
Here is the calculation:
Select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' +
right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from tblTime
Output: 0:45:00
Live Demo
declare #time1 varchar(8) = '00:25:00';
declare #time2 varchar(8) = '00:20:00';
select CONVERT(varchar(8),
DATEADD (SECOND ,
(CONVERT(int, LEFT(#time1, 2))*60*60 /* hours in seconds*/
+ CONVERT(int, substring(#time1,4,2)*60) /* minutes in seconds*/
+ CONVERT(int, RIGHT(#time1, 2)))/* seconds only */
, '19000101 ' + #time2
)
,108)/* convert back to time format*/
You can also try as,
create table timeSum (value1 varchar(50), value3 varchar(50))
insert into timeSum values ('00:45', '00:10')
Calculation
select Convert(Varchar,(Convert(DateTime,Value1 )+Convert(DateTime,value3)),114) as TotalTime from timeSum
Out Put: 00:55:00:000
Remarks :
I recommended you to use DateTime or Time datatype for in Date or Time related field.
I have figured it out:
select convert(decimal(18, 2), convert(decimal(18, 2), ppt.hour) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.minute/ 60)) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.second / 3600))) AS Hours, ppt.[column] from (select SUM(convert(decimal(2),left([column], 2))) AS hour, SUM(convert(decimal(2), left(right([column], 5), 2))) AS minute, SUM(convert(decimal(2), right([column], 2))) AS second, [column] FROM [table] GROUP BY [column]) AS ppt

Sum of time in sql

I have a table like this...
create table test
(
dt datetime
)
In that table the datetime are as follows,
2011/02/02 12:55:00
2011/03/05 00:40:00
2011/02/03 00:12:00
I want to calculate sum hours,mi,ss
In a single Select query not sp.
If any one know please tell me.
Thanks ...
You could sum the times as seconds, then convert to hours, minutes and seconds:
select TotalSeconds / 3600 as [Hours], (TotalSeconds % 3600) / 60 as [Minutes], (TotalSeconds % 3600) % 60 as [Seconds]
from
(
select sum(datepart(hour, dt) * 3600) + sum(datepart(minute, dt) * 60) + sum(datepart(second, dt)) as TotalSeconds
from test
) t
Assuming the sum won't be more than 999 hours:
DECLARE #t TABLE(dt DATETIME);
INSERT #t SELECT '20110202 12:55'
UNION SELECT '20110305 00:40'
UNION SELECT '20110203 00:12';
WITH s AS
(
SELECT s = SUM(DATEDIFF(SECOND,
DATEADD(DAY, 0, DATEDIFF(DAY, 0, dt)), dt))
FROM #t
)
SELECT
s,
hhmmss = RIGHT('000' + RTRIM(s/3600), 3)
+ ':' + RIGHT('00' + RTRIM((s % 3600) / 60), 2)
+ ':' + RIGHT('00' + RTRIM((s % 3600) % 60), 2)
FROM s;
However, if what you are really storing is duration, why not store the number of seconds instead of wedging your data into an inappropriate data type that requires all kinds of workarounds to process properly?
Declare #Table Table
(
DateTimeCol DateTime
)
insert into #Table values ( '2011/02/02 12:55:00')
insert into #Table values ('2011/03/05 00:40:00')
insert into #Table values ('2011/02/03 00:12:00')
;with CTE As
(
--first of all find total seconds of datecolumn
--sum all seconds
Select SUM(
(datepart(hour,DateTimeCol)*60*60)+(datepart(minute,DateTimeCol)*60)+(datepart(second,DateTimeCol))
) As TotalSecond
From #Table
)
--devides with 3600 to get the total hours and then to 60 to get total minutes
Select CONVERT(VARCHAR(10),TotalSecond/3600)+ '.' +
CONVERT(VARCHAR(20),TotalSecond%3600/60) + '.' +
CONVERT(VARCHAR(20),TotalSecond%3600%60) AS [Time] --Total of Time
From CTE

how to get sum() from alise column in SQL

I'd like the sum of TotalVisitedTime time but it is alias column so how can I gtt it?
Select CONVERT(varchar(6), DATEDIFF(second, [Start], [End])/3600)
+ ':'
+ RIGHT('0' + CONVERT(varchar(2), (DATEDIFF(second, [Start], [End]) % 3600) / 60), 2)
+ ':'
+ RIGHT('0' + CONVERT(varchar(2), DATEDIFF(second, [Start], [End]) % 60), 2) AS TotalVisitedTime
FROM [Table Name]
Note: [Start] and [End] are columns name.
SELECT SUM(TotalVisitedTime)
FROM (
-- AS PER #Alex Aza, #Andriy M
SELECT 1234 AS TotalVisitedTime
) AS OuterTable
I think it makes sense to sum up seconds and then do the conversion you are trying to do.
SELECT CONVERT(varchar(6), diff/3600)
+ ':'
+ RIGHT('0' + CONVERT(varchar(2), (diff % 3600) / 60), 2)
+ ':'
+ RIGHT('0' + CONVERT(varchar(2), diff % 60), 2) AS TotalVisitedTime
FROM
(
select sum(DATEDIFF(second, [Start], [End]) diff
from [Table Name]
) tt