I have a sum of difference between dates in a Sql table. How do I calculate its average in days, hours, minutes? - sql

I have a table with a start time and an end time (datetime, example: 2021-07-09 17:12:00) in each row.
When I calculate the sum of all differences between end time and start time by this SQL query:
SELECT
TIME(SUM(TIMEDIFF(`end_time`, `start_time`))) AS TimeDiff
FROM
my_table
I get a result expressed in hours, minutes, seconds (example: 00:02:00)
Now I need to calculate the average time expressed in hours, minutes, seconds of this sum.
It means:
SELECT
TIME(SUM(TIMEDIFF(`end_time`, `start_time`))) AS TimeDiff
FROM
my_table
TimeDiff/number of rows (expressed in hours, minutes, seconds)
Can you help me? Really thanks

Going out on a limb and guessing you're using MySQL due to the TIMEDIFF function.. Always state what DB you use; SQL is a standard, not a product
You asked about converting times to seconds and back, it probably looks like:
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(end_time, start_time)))) FROM ...

Related

sql statement - would like to subtract 1 date from another and get the days hours and mins inbetween

I would like to subtract 1 date from another and get the days hours and mins in-between.
I know there is a DateDiff function, however it does not work with all 3 time values; days hours and mins. I would like this doable in an SQL statement. Currently I have the following.
SELECT id, pickupdateandtime, GETDATE() AS CurrentTime,
(DATEDIFF(day,GETDATE(),pickupdateandtime)) AS Days,
(DATEDIFF(hour,GETDATE(),pickupdateandtime)) AS Hours,
(DATEDIFF(minute,GETDATE(),pickupdateandtime)) AS Mins FROM orders
And it shows up like this:
If we can stick it all in 1 column that's fine too.
I agree with #AndyMcLaughlin about the use of the mod operator % here. It's very handy for this sort of thing. However, I have a general distrust of DATEDIFF. That function does not count the whole number of years (say) between two dates, but the number of year boundaries between them.
So DATEDIFF "thinks" the difference in years between 01-Jan-2000 and 01-Jan-2001 is the same as that between 31-Dec-2000 and 01-Jan-2001.
This is why #Michael saw a need to subtract 1 from #AndyMcLaughlin's results. Unfortunately, that doesn't always work, it will depend on the individual case.
As a rule, DATEDIFF works well when it's used against the smallest interval you are interested in. So if you are interested in years and simply want to separate one calendar year from another, it'll serve you well.
I think the smallest interval we are interested in here is minutes. So we can use DATEDIFF for that, but have to work upwards from there to hours and days:
select
mf.id,
mf.pickupdateandtime,
mf.CurrentTime,
--The divisions in the following lines simply
--truncate since all the numbers are integers
--but that works in our favour here
(mf.MinutesFull/(60*24)) as Days,
(mf.MinutesFull/60) % 24 as Hours,
mf.MinutesFull % 60 as Minutes
from
(
select
id,
pickupdateandtime,
getdate() as CurrentTime,
datediff(minute, getdate(), pickupdateandtime) as MinutesFull
from #orders
) mf
You need to use the mod operator % to remove whole days from hours and whole hours from minutes.
So you can do something like:
SELECT
id,
pickupdateandtime,
GETDATE() AS CurrentTime,
(DATEDIFF(day,GETDATE(),pickupdateandtime)) AS Days,
(DATEDIFF(hour,GETDATE(),pickupdateandtime) % 24) AS Hours,
(DATEDIFF(minute,GETDATE(),pickupdateandtime) % 60) AS Mins FROM orders

Sql Query information

What does this do in a SQL Query? Can someone explain? What does the .5- represent?
WHERE ScheduleEntry.ScheduleDate >= getdate() and ScheduleEntry.ScheduleDate <= getDate() +.50
Think of date unit as 1 day. 0.50 of a day is 1/2 of a day. So this returns anything that has ScheduleDate within half a day from getdate() time forward.
It restricts the rows returned to rows where the ScheduleEntry.ScheduleDate is in the future and where it is not more than .50 units later than the current date. To find out how much time .50 units is equal to, run the following on your console:
SELECT getDate()
SELECT getDate() +.50
The difference between the dates should tell you the difference. Most likely, it is half a day.
GETDATE returns the current date and time in SQL.
You can use addition to "add days" to the current date.
Generally, it is better to use DATE_ADD instead of adding directly and is probably easier to read. Adding 0.5 is akin to adding half a day (or 12 hours).
To better illustrate, the .5 is half a day
SELECT DateDiff(HH,getDate(),getDate() +.50)
Returns 12 hours

In SQL, how can I count rows grouping into certain intervals, if I only know the length of those intervals?

Let's say that my first column is time. What I want is to be able to count the rows grouping them by an arbitrary time range, for instance: by day, by hour, by 20 minutes intervals, by 15 seconds etc.
Convert the timestamp into some appropriate number (here: number of seconds since the Unix epoch), then do an integer division by the number of seconds (which implicitly rounds down):
SELECT ...
GROUP BY strftime('%s', MyDate) / 15 -- or 20*60 etc.

Aggregate and calculate total minutes for set of records as productivity

I have a table that lists activity for people and start / end timed for activity.
How do I get total amount of records for each person?
SELECT NAME,
--sum(startDT- endDT) AS minutes -- stuck here
FROM TABLE1
GROUP BY NAME
You're subtracting end time from start time, which will produce a negative value - try flipping those around (subtract start time from end time). The following will give you the number of records and the total elapsed time for each NAME:
SELECT NAME,
COUNT(*) AS "Records for NAME",
TO_CHAR(NUMTODSINTERVAL(SUM(END_DATE_TIME - START_DATE_TIME), 'DAY')) AS MINUTES
FROM TABLE1
GROUP BY NAME
SQLFiddle here
Share and enjoy.
Assuming that startDT and endDT are both of type date, you were really close. Subtracting two dates gives a difference in days. Multiply by 24 to get a difference in hours and again by 60 to get minutes
SELECT NAME,
sum(endDT - startDT)*24*60 AS minutes -- stuck here
FROM TABLE1
GROUP BY NAME
Assuming that your differences aren't always an exactly even number of minutes, you'll either get a non-integer result (e.g. 12.5 for 12 minutes 30 seconds) here or you'll want to either round or trunc the sum to get an integer number of minutes.

How to subtract 1 minute from hour

I have a query contains from time and to time parameters.
I need to subtract 1 minute from totime parameter.
I used totime-1.
It is working in database level and it is not working in my crystal reports.I mean it is subtracting 1 hour in report level.
Can any one please tell me other formula for subtracting a minute.
Thanks,
vissu
If you are using SQL Serve/T-sql
DATEADD(MI, -1, totime)
In some databases (SQL Server and Oracle for instance), you can do the following:
select totime - 1.0/(24*60)
Time differences are measured in days, so 1.0/(24*60) is one minute represented as a fraction of a day.
MySQL accepts the syntax, but the timestamp is measured in seconds not days, so you would use:
select totime - 60