--建表CREATETABLE`test`(`id` string,`checkin`timestamp,`checkout`timestamp)--插入数据insertintotable test select'1',cast('2022-04-04 08:00:10'astimestamp),cast('2022-04-04 11:20:20'astimestamp);insertintotable test select'1',cast('2022-04-04 02:00:03'astimestamp),cast('2022-04-04 03:40:30'astimestamp);insertintotable test select'1',cast('2022-04-04 04:17:11'astimestamp),cast('2022-04-04 07:44:46'astimestamp);insertintotable test select'1',cast('2022-04-04 07:50:11'astimestamp),cast('2022-04-04 07:59:59'astimestamp);
id
checkin
checkout
1
2022-04-04 08:00:10
2022-04-04 11:20:20
1
2022-04-04 04:17:11
2022-04-04 07:44:46
1
2022-04-04 07:50:11
2022-04-04 07:59:59
1
2022-04-04 02:00:03
2022-04-04 03:40:30
逻辑实现
select
id,
to_date(checkin2) check_date,hour(checkin2) check_hour,
checkin2 checkin,if(unix_timestamp(checkout2)>unix_timestamp(checkout),checkout,checkout2) checkout
from(select
id,
sign,
checkout,casewhen sign<>0then concat(date_format(checkin,'YYYY-MM-dd'),' ',if(length((hour(checkin)+sign))=1,concat('0',cast((hour(checkin)+sign)as string)),cast((hour(checkin)+sign)as string)),':00:00')else checkin end checkin2,casewhenhour(checkin)<>hour(checkout)then concat(date_format(checkin,'YYYY-MM-dd'),' ',if(length((hour(checkin)+sign+1))=1,concat('0',cast((hour(checkin)+sign+1)as string)),cast((hour(checkin)+sign+1)as string)),':00:00')else checkout end checkout2
from(select*from lx_time
) tmp lateral view posexplode(
split(space(hour(checkout)-hour(checkin)+(datediff(checkout,checkin))*24),'')) t as sign,sign2
) f ;