How to Sum (Time(n)) in Sql Server? - sql

How want to use the sum of the time(n) operator so that i can calculate the overall total of the time but Sql server saying can't add the Time(n) column
i have a casted column which contain difference of two dates, and being casted as Time(n) by me. Now i want to add those column to get how much time i had used in total How much hours minute and seconds so i apply
select Sum(cast ((date1-date2) as Time(0))) from ABC_tbl
where date1 is reaching time and date2 is startingtime in Date format and i want to total of all hours

Convert the time to an integer value before you sum it (for example, seconds):
SELECT SUM(
datediff(second, '00:00:00', [TimeCol])
)
FROM
...
Replace [TimeCol] with the name of the Time(n) column. This gives you the total time in seconds, which you can then easily convert to minutes, hours, etc...

Hope this example help you.
DECLARE #A TABLE (SD TIME(0),ED TIME(0))
INSERT INTO #A VALUES
('09:01:09','17:59:09'),
('09:08:09','16:10:09'),
('08:55:05','18:00:00')
SELECT SUM(DATEDIFF(MINUTE,SD,ED)) SUM_IN_MINUTES,
SUM(DATEDIFF(HOUR,SD,ED)) SUM_IN_HOURS
FROM #A
Result:
SUM_IN_MINUTES | SUM_IN_HOURS
---------------------------------------
1505 | 25

select Sum(DATEDIFF(Minute,date1,date2)) AS TIME from ABC_tbl
u have to calculate the date difference with DATEDIFF function then use SUM function to calculate your sum of time.
you can change Minute to Second-Hour-month etc..

Try this:
DECLARE
#MidnightTime TIME = '00:00:00.0000000',
#MidnightDateTime DATETIME2 = '0001-01-01 00:00:00.0000000';
SELECT SumOfTime = DATEADD(SECOND, SUM ( DATEDIFF(SECOND, #MidnightTime, x.Col1) ), #MidnightDateTime)
FROM (VALUES
(1, CONVERT(TIME, '10:10:10.0000001')),
(2, CONVERT(TIME, '00:00:05.0000002')),
(3, CONVERT(TIME, '23:59:59.0000003'))
) x(ID, Col1)
/*
SumOfTime
---------------------------
0001-01-02 10:10:14.0000000 = 1 day (!), 10 hours, 10 minutes, 14 seconds
*/
Note: instead of SECOND you could use another precision: MINUTE, HOUR or ... NANOSECOND (see section Arguments > datepart). Using a higher precision could leads to Arithmetic overflow errors (use CONVERT(BIGINT|NUMERIC(...,0), ...).
Note #2: because the precision is SECOND the result (SumOfTime) has 0000000 nanoseconds.

Related

How to calculate exact hours between two datetime fields?

I need to calculate hours between datetime fields and I can achieve it by simply doing
select date1,date2,(date1-date2) from table; --This gives answer in DD:HH:MM:SS format
select date1,date2,(trunc(date1)-trunc(date2))*24 --This doesn't take into account the time, it only gives hours between two dates.
Is there a way I can find the difference between date times that gives the output in Hours as a number?
The 'format' comment on your first query suggests your columns are timestamps, despite the dummy column names, as the result of subtracting two timestamps is an interval. Your second query is implicitly converting both timestamps to dates before subtracting them to get an answer as a number of days - which would be fractional if you weren't truncating them and thus losing the time portion.
You can extract the number of hours from the interval difference, and also 24 * the number of days if you expect it to exceed a day:
extract(day from (date1 - date2)) * 24 + extract(hour from (date1 - date2))
If you want to include fractional hours then you can extract and manipulate the minutes and seconds too.
You can also explicitly convert to dates, and truncate or floor after manipulation:
floor((cast(date1 as date) - cast(date2 as date)) * 24)
db<>fiddle demo
Use the DATEDIFF function in sql.
Example:
SELECT DATEDIFF(HOUR, '2021-09-05 12:00:00', GETDATE());
You can find it using the differnece of dates and multiplying with 24
select date1
,date2
,(date1-date2)*24 as diff_in_hrs
from table

Average Time on SQL

I am working on a report where I need to find the average amount of time between two timestamps.
To find the time between the time stamps I used:
CAST(( Time2 - Time1 ) as time(0)) AS 'Time Between Stage1 and Stage2'
Now that I have that column, I am trying to get the Average Time Spent Between Stage1 and Stage2. I'm looking for the output to be in the hh:mm:ss format.
Try this:
Format(AVERAGE(CAST(( Time2 - Time1 ) as time(0)), "HH:MM: SS"))
declare #t1 datetime, #t2 datetime
set #t1 = '14:15:54'
set #t2 = '15:12:33'
select #t1,#t2
select cast(dateadd(ms, AVG(datediff( ms, #t1 ,#t2 )), '00:00:00') as time)
First, find the difference using DateDiff in the format of the lowest grain.
Then, find the average
Convert the Average back to date using the DateAdd (you will get errors if you try to use a cast or convert)
Finally, Cast back to a time
replace the variables with your attributes

how to get sum of time as float

A table has a time column in float datatype is given as:
40m
11m
2m
0m
3m
1m
1m
How can I sum these values to get it in hours and minutes?
You could use Gordon's answer, which directly leverages SQL Server's built in time ability. An alternative would be the "brute force" approach of computing the number of hours and minutes represented by the sum of your time column:
WITH cte AS (
-- strip off 'm' units and convert to numbers
SELECT CONVERT(int, REPLACE(time, 'm', '')) AS time
FROM yourTable
)
SELECT
CONVERT(varchar(10), FLOOR(SUM(time) / 60)) + ':' +
CONVERT(varchar(10), FLOOR(SUM(time) % 60)) AS timestamp
FROM cte;
Demo
The demo shows that the logic holds up even if the number of minutes in your column should exceed 24 hours.
You can use dateadd() and then cast the result back to a time:
select cast(dateadd(minute, sum(col), 0) as time)
from t;
Note: This only works up to 23:59:00. The SQL Server time type does not support larger values.
Here is a rextester.

How can I find exact number of minutes without rounding between two dates in sql server

I am new to Sql server, I tried datediff several times but failed. All I need is the exact or precise number of minutes including fraction between two dates. E.g if the gap between two datetime fields is 40 seconds than it gives me 0.67 minutes and not 1 minute. Please help.
Take the difference in seconds and divide by 60.0:
select datediff(second, date1, date2) / 60.0 as diff_in_minutes
This should be close enough for most work. If you really want, you could use milliseconds instead of seconds.
select datediff(millisecond, date1, date2) / 60000.0 as diff_in_minutes
To get MILLISECOND accurate value
DECLARE #D1 DATETIME = '2015-04-16 21:38:02.610'
DECLARE #D2 DATETIME = '2015-04-16 21:38:29.023'
SELECT DATEDIFF(MILLISECOND, #D1, #D2)* 1.000 / ((1.66667) * POWER(10,5))
RESULT: 0.158477683044633910732

Calculate the time after converting into a new datatype

Goal:
To display data with this list:
Hour
-----
2
2,5
1
Problem:
Is it any possibiltiy to convert column StartTime and EndTime into specific datatype and then doing a calculacution of X1- X2
CREATE TABLE Data
(
StartTime VARCHAR(5),
EndTime VARCHAR(5),
)
GO
INSERT INTO Data(StartTime,EndTime)
SELECT '10:00','12:00' UNION ALL
SELECT '13:30','16:00' UNION ALL
SELECT '14:00','15:00' UNION ALL
GO
EDITED: To get mins in decimals
SELECT ROUND(CAST( Mins AS FLOAT)/60,2) AS [hour]
FROM (
SELECT DATEDIFF(minute, CAST(StartTime AS TIME),CAST(EndTime AS TIME)) AS Mins
FROM Data
) A
SELECT DATEDIFF(mi, CONVERT(DATETIME, StartTime), CONVERT(DATETIME, EndTime))
/ 60.0 AS Hour
FROM Data
It work's for your example data, but you should check if EndTime could be the next day, like:
StarTime: 22:30
EndTime: 01:20
Is that escenario possible? If it is, you must store the date for both Start and End times, not only the hour.
If you are using SQL-SERVER 2008, then why not just use the time object. You could then run the appropriate time comparison functions. If not, you can still make it work by converting to a datetime and running comparison functions. I believe a convert with just a time to a datetime will result in the date as the minimum date.