从表中获取下一个日期记录

问题描述 投票:0回答:1

我有这样的出勤表:

员工 日期_时间 状态
std001 2024-02-01 22:01:00
std001 2024-02-02 06:00:05
std001 2024-02-03 07:59:00
std001 2024-02-03 17:00:00
std001 2024-02-04 06:00:00
std001 2024-02-04 14:00:00

我想选择上面的表格以获得如下结果:

员工 日期 日期时间_输入 日期时间_输出
std001 2024-02-01 2024-02-01 22:01:00 2024-02-02 06:00:05
std001 2024-02-02 2024-02-02 06:00:05
std001 2024-02-03 2024-02-03 07:59:00 2024-02-03 17:00:00
std001 2024-02-04 2024-02-04 06:00:00 2024-02-04 14:00:00

“DateTime_In”来自状态为“IN”的“Date_Time”,如果“DateTime_In”为 < 22:00:00 then the "DateTime_Out" is the "Date_Time" with status "OUT" from same date. but if the "DateTime_In" >= 22:00:00,则“DateTime_Out”是状态为“OUT”的第二天的“Date_Time” .

任何人都可以帮我在mysql服务器中查询吗?谢谢!

mysql join subquery
1个回答
0
投票

请: 该查询应该完全按照您的需要工作:

select 
    DATE_FORMAT(Date_Time,'%Y-%m-%d') as Date,
    Date_Time as DateTime_In,
    if(Status='IN' and Date_Time < concat(DATE_FORMAT(Date_Time,'%Y-%m-%d'),' 22:00:00'),
        (select Date_Time from tmp as tmpif1 where Status='Out' and DATE_FORMAT(tmpif1.Date_Time,'%Y-%m-%d')=DATE_FORMAT(tmp.Date_Time,'%Y-%m-%d')),
        (select Date_Time from tmp as tmpif2 where Status='Out' and DATE_FORMAT(tmpif2.Date_Time,'%Y-%m-%d')=DATE_FORMAT(DATE_ADD(tmp.Date_Time,INTERVAL 1 DAY),'%Y-%m-%d'))) as DateTime_Out
        
    from tmp
    where Status='IN';
© www.soinside.com 2019 - 2024. All rights reserved.