[英]SQL query to find total hour of between start date and end date
這是我的示例表
id from_time to_time user_login_id
1 1583721900 1583782500 2
2 1583721900 158378255 2
3 1583721900 1583782555 5
4 1583721900 1583782555 3
(日期時間存儲在 UNIX 時間戳中)
我希望 SQL 查詢在給定日期內獲取開始和結束之間的總小時數
例如:我想從表中獲取 01-02-2020 到 31-02-2020 之間的總小時數
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
輸出:
user_login_id total_hour
2 4
它應該從 01-01-2020 之后開始的時間到 31-01-2020 之前結束的時間給出
提前致謝
這可能會按您的預期工作
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.