我有一个MySQL表,记录员工登录和注销时间。在输入输出列1中表示登录,0表示登出。
[id] [User_id] [Date_time] [in_out]
1 1 2011-01-20 18:01:03 1
2 1 2011-01-20 19:30:43 0
3 1 2011-01-20 20:46:23 1
4 1 2011-01-21 00:42:45 0
用户可以使用单个查询检索一天(2天之内)的总工作小时数吗?
同一个问题是Get total hours worked in a day mysql和解决方案的副本:
SELECT `User_id`, time(sum(`Date_time`*(1-2*`in_out`)))
FROM `whatever_table` GROUP BY `User_id`;
但是当员工一天开始工作而第二天出去时,解决方案需要有所不同。
答案 0 :(得分:1)
您可以使用给定的存储过程实现此目的。考虑一下您的表名EventLog
。
DELIMITER $$
CREATE PROCEDURE `GET_TOTAL_LOGIN_TIME`(
IN startDate DATETIME,
IN endDate DATETIME,
IN userId INT(11)
)
BEGIN
select
(sum(
case when(e2.Date_time <= startDate) then 0 else
case when(e1.Date_time >= endDate) then 0 else
case when(e1.Date_time >= startDate && e2.Date_time <= endDate) then
TIME_TO_SEC(TIMEDIFF(e2.Date_time, e1.Date_time))/60 else
case when(e1.Date_time <= startDate && e2.Date_time <= endDate) then
TIME_TO_SEC(TIMEDIFF(e2.Date_time, startDate))/60 else
case when(e1.Date_time >= startDate && e2.Date_time >= endDate) then
TIME_TO_SEC(TIMEDIFF(endDate,e1.Date_time))/60
end end end end end
)) as loginTimeInMin
from
((EventLog e1
left join EventLog e2 ON (((e1.User_id = e2.User_id) and (e2.in_out = 0) and (e1.Date_time < e2.Date_time))))
left join EventLog e3 ON (((e1.User_id = e3.User_id) and (e1.Date_time < e3.Date_time) and (e3.Date_time < e2.Date_time))))
where
((e1.in_out = 1) and isnull(e3.Date_time)) and e2.Date_time is not null
AND e1.User_id = userId
AND userRole.userRoleId = roleId
AND userRole.userLoginId = userId
group by e1.User_id;
END;
答案 1 :(得分:0)
你可以得到这样的秒数:
SELECT `User_id`, sum(unix_timestamp(`Date_time`)*(1-2*`in_out`))
FROM `whatever_table`
GROUP BY `User_id`;
然后你可以把秒转换成你想要的任何东西。