MySQL add up time duration of entries [duplicate] - mysql

How to caculate sum of times of my colonne called "timeSpent" having this format: HH:mm
in SQL? I am using MySQL.
the type of my column is Time.
it has this structure
TimeFrom like 10:00:00 12:00:00 02:00:00
TimeUntil 08:00:00 09:15:00 01:15:00
Time spent
total time 03:15:00

SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `timeSpent` ) ) ) AS timeSum
FROM YourTableName

100% working code to get sum of time out of MYSQL Database:
SELECT
SEC_TO_TIME( SUM(time_to_sec(`db`.`tablename`)))
As timeSum
FROM
`tablename`
Try and confirm.
Thanks.

In MySQL, you would do something like this to get the time interval:
SELECT TIMEDIFF('08:00:00', '10:00:00');
Then to add the time intervals, you would do:
SELECT ADDTIME('01:00:00', '01:30:00');
Unfortunately, you're not storing dates or using 24-hour time, so these calculations would end up incorrect since your TimeUntil is actually lower than your TimeFrom.
Another approach would be (assuming you sort out the above issue) to store the time intervals as seconds using TIMESTAMPDIFF():
UPDATE my_table SET time_spent=TIMESTAMPDIFF(start, end));
SELECT SEC_TO_TIME(SUM(time_spent)) FROM my_table;

If the data type of the timeSpent column is TIME you should be able to use the following query:
SELECT SUM(timeSpent)
FROM YourTableName -- replace YourTableName with the actual table name
However, if that is not the case, you may have to use a cast to convert to the Time data type. Something like this should work:
SELECT SUM(timeSpent - CAST('0:0:0' as TIME))
FROM YourTableName -- replace YourTableName with the actual table name

Related

Hourly counting MySQL

Since few days, I am trying to count records per hour from the MySQL database.
I have a table with a lot of records and I have column DATE and column TIME where in DATE I have the date of the record in the format 2022-05-19, and in the column TIME, I have the time of the record in the format 14:59:38.
What I am trying is to count every single day how many records per hour I have. Something like this:
DATE HOUR PCS
22-05-18 06-07 11
22-05-18 08-09 20
......... ..... ..
....... 21-22 33
I have tried many different ways but no success.
For example:
SELECT 'Date', count(*) FROM `root4`
where
DATE between '2022-05-01' and '2022-05-1' AND
TIME BETWEEN '06:11:05' AND '07:11:05'
Any help is highly evaluated.
I would recommend not using reserved words for columns, as you will have to escape them a lot. https://dev.mysql.com/doc/refman/8.0/en/keywords.html
If you stored TIME as a timestamp, you can extract the hour using the HOUR() function and group by that:
SELECT
`DATE`,
HOUR(`TIME`) AS `HOUR`,
COUNT(1)
FROM your_table
GROUP BY
`DATE`,
HOUR(`TIME`)
If you happened to store it as text you can use REGEXP_SUBSTR to get the hour value from your time string.
SELECT
`DATE`,
CAST(REGEXP_SUBSTR(`TIME`, '[0-9]+') AS UNSIGNED) AS `HOUR`,
COUNT(1)
FROM your_table
GROUP BY
`DATE`,
CAST(REGEXP_SUBSTR(`TIME`, '[0-9]+') AS UNSIGNED)
You can format your HOUR column how you want, like displaying 01-02 instead of 1 by using CONCAT, but this is your basic setup.

Query data between the same date

Is it possible to do something like this?
select * from table where Date BETWEEN '2019-05-29' AND '2019-05-29'
Yes it is possible. If you have time part you could use DATE function to skip it:
SELECT * FROM table WHERE DATE(Date) BETWEEN '2019-05-29' AND '2019-05-29'
-- it may degrade performance, condition is not SARGable
Yes, but the better approach is:
select t.*
from table t
where t.Date >= date('2019-05-29') AND
t.Date < date('2019-05-29') + interval 1 day
Why is this better? It doesn't have a function on the column name, so it can make use of an index on the date column.
Yes you can, if you want to run it in a test window without manually changing the date within the code you can set it as a variable. Use trunc to get rid of time i.e there will be no 29-05-2019 23:59:00. If you want the same date within a time period remove the trunc and then you can set hours-minutes-seconds which makes your query more precise
SELECT t.*
FROM table t
WHERE t.date BETWEEN trunc(to_date(:datefrom, 'dd.mm.yyyy hh24:mi:ss')) AND
trunc(to_date(:dateto, 'dd.mm.yyyy hh24:mi:ss'))

MySQL Trigger - timestamp hour between?

I'm after a mysql trigger that will set the column peak to 0 or 1 based on the timestamp hour between 08:01 & 23:59.
Can anyone help?
example:-
userstats.timestamp = 2018-07-01 12:27:20
peak = 1
One option is to use the DATE_FORMAT function to isolate the time component of your timestamp, e.g.
SELECT *
FROM userstats
WHERE DATE_FORMAT(timestamp, '%H:%i') BETWEEN '08:01' AND '23:59';
Your actual query may not look exactly like this, but this would seem to answer the crux of your question.

SQL query doesn't work on a specific day

I have a weird problem in mysql!
my query is
SELECT * FROM aa WHERE problemTime>= '2016/03/20' AND problemTime<= '2016/04/20'
the result of this query is nothing , but when I change the first time to 2016/03/19 or 2016/03/21 I have the following result! I mean these queries
SELECT * FROM aa WHERE problemTime>= '2016/03/21' AND problemTime<= '2016/04/20'
or
SELECT * FROM aa WHERE problemTime>= '2016/03/19' AND problemTime<= '2016/04/20'
the result in both time ( 19th and 21th) is
but when I use 20th the result is noting
my main table is
I change the format of time from 2016/03/20 to 2016-03-20 ( I mean change / to - ) but it doesn't have change too!
whats the problem?
You should really be running a query like this if your problemTime column is datetime type:
SELECT * FROM aa
WHERE
problemTime>= str_to_date('2016/03/20', '%Y/%m/%d') AND
problemTime <= str_to_date('2016/04/20', '%Y/%m/%d')
Don't rely on implicit conversions between string and date.. leave your table data alone and ensure you explicitly convert your where clause parameters to the same data type as in the table. Also remember that a date "without" a time is actually midnight on the day in question, and midnight is like zero, it's the first thing that happens on any given day. A time of 6am on a given date, is after midnight, so a query that asks for dates less than or equal to midnight on a particular date means the 6am date will be excluded
This is general good DB practice; do not convert table data where possible, because it can cause huge performance hits and wrong results
Your column "problemTime" have date with time. Do not convert table data, change your where clause (add time).
SELECT * FROM aa WHERE problemTime>= '2016/03/20 00:00:00' AND problemTime<= '2016/04/20 23:59:59'
Try this as per SQl Server.
SELECT * FROM aa
WHERe cast(problemTime AS date) between '2016/03/21' AND '2016/04/20'

setting up a mysql database to record tasks

I am trying to setup a MySQL database using PHPMyAdmin. Before I get long into it I want advice on setting it up and querying it. I set the table like this.
id: primary ket
time_in: date
time_out: date
task: varchar (128)
business: varchar (128)
All I need it to do is to keep track of how much time spent on each task and for what business. Is this good way of doing it or is there a better way?
If this is correct then I am trying to figure out how to query the time. This is what I have come up with as a query, but it far from what I want.
SELECT `Task`,`Business`, (SELECT `Time-Out` - `Time-In`) as `total time` FROM `Sheet`
Is there a way to convert total time into a more readable format?
Unless you're tracking time in days, I'd recommend using TIME or DATETIME for the time_in and time_out columns.
Personally, I'd probably make time_out nullable, to allow tracking current activity (something I've started, but not yet finished).
There's no need to use a sub-select for subtracting the timestamps, you can subtract those two columns inline as well (just drop the SELECT keyword there). For formatting, you could use the TIMEDIFF function:
SELECT '12:00:00' - '10:45:00';
-> 2
SELECT TIMEDIFF('12:00:00', '10:45:00');
-> '01:15:00'
That would make your query:
SELECT `Task`, `Business`, TIMEDIFF(`Time-Out`, `Time-In`) as `total time` FROM `Sheet`
If you do make time_out (or Time-Out) nullable, you'll need to take that into account in your query:
SELECT TIMEDIFF(NULL, '10:45:00');
-> NULL
So ongoing tasks would give a total time of NULL. If you want to know how long you've been working already, you can wrap it in an IFNULL function and get the current time in that case:
SELECT TIMEDIFF(IFNULL(`Time-Out`, NOW()), `Time-In`);
-> '01:15:00' if `Time-Out` is 12:00:00 and `Time-In` is 10:45:00
-> '02:05:13' if `Time-Out` is NULL and it's currently 12:50:13 (server time)
You will want to use TIMEDIFF(end_time, start_time) and TIME_TO_SEC(time) to convert the difference to a total number of seconds. You can then convert the seconds mathematically to whatever format you want.
So for the time of each task:
select ID
,task
,business
,time_to_sec(timediff(time_out, time_in)) as duration
from sheet
To aggregate by task and business:
select task
,business
,sum(time_to_sec(timediff(time_out,time_in))) as total_time
from sheet
group by task
,business