Reputation: 145
Here is my sample table
id from_time to_time user_login_id
1 1583721900 1583782500 2
2 1583721900 158378255 2
3 1583721900 1583782555 5
4 1583721900 1583782555 3
(date times are stored in UNIX time stamp )
I wanted SQL query to fetch sum of total hour between started and ended within given date
For ex: i wanted fetch total hour between 01-02-2020 to 31-02-2020 from table
from-time to_time user_login_id
01-01-2020 10:00 01-01-2020 12:00 1
01-2-2020 10:00 02-01-2020 12:00 1
02-02-2020 10:00 02-02-2020 12:00 2
03-02-2020 10:00 03-02-2020 12:00 2
Output:
user_login_id total_hour
2 4
It should give from time started after 01-01-2020 and close time ended before 31-01-2020
Thanks in advance
Upvotes: 0
Views: 249
Reputation: 842
This may work as you expect
SELECT FROM_UNIXTIME(`from_time`,'%Y-%m-%d %h:%i:%s'),FROM_UNIXTIME(`to_time`,'%Y-%m-%d %h:%i:%s'),user_login_id,SUM(TIMESTAMPDIFF(HOUR, FROM_UNIXTIME(`from_time`,'%Y-%m-%d %h:%i:%s'),FROM_UNIXTIME(`to_time`,'%Y-%m-%d %h:%i:%s'))) as total_hour
FROM
your_table_here
WHERE
(FROM_UNIXTIME(`to_time`,'%Y-%m-%d') BETWEEN STR_TO_DATE("01-03-2020",'%d-%m-%Y') and STR_TO_DATE("31-03-2020",'%d-%m-%Y')) and
(FROM_UNIXTIME(`from_time`,'%Y-%m-%d') BETWEEN STR_TO_DATE("01-03-2020",'%d-%m-%Y') and STR_TO_DATE("31-03-2020",'%d-%m-%Y'))
GROUP BY `user_login_id`
//here 01-03-2020 is considered as start date and 31-03-2020 is end date that you have to make dynamic
//note :- it will produce result only in hours and ignore minute difference if any
Upvotes: 1