题解 | 查询连续入住多晚的客户信息?

select
    ct.user_id,
    ct.room_id,
    gt.room_type,
    sum(DATEDIFF (ct.checkout_time, ct.checkin_time)) as days
from
    guestroom_tb gt
    inner join checkin_tb ct on gt.room_id = ct.room_id
where
    ct.checkout_time >= '2022-06-12 00:00:00'
group by
    ct.user_id,
    ct.room_id,
    gt.room_type
having
    days > 1
order by
    days asc,
    ct.room_id asc,
    ct.user_id desc

执行逻辑

  1. FROM 和 JOIN:从 guestroom_tb 和 checkin_tb 表中通过 room_id 进行连接。
  2. WHERE:筛选出 checkout_time 大于或等于 2022-06-12 15:00:00 的记录。
  3. GROUP BY:按 ct.user_id、ct.room_id 和 gt.room_type 进行分组。每个分组包含具有相同 user_id、room_id 和 room_type 的记录。
  4. SUM(DATEDIFF(ct.checkout_time, ct.checkin_time)):对每个分组内的记录,计算 checkout_time 和 checkin_time 之间的天数差(DATEDIFF)。将每个分组内的天数差进行累加(SUM),得到该分组的总天数。
  5. SELECT:选择每个分组的 user_id、room_id、room_type 和总天数(days)。
  6. ORDER BY:按 days,user_id 和 room_id 对最终结果进行排序。
全部评论

相关推荐

牛客84809583...:举报了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务