You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle SQL按分区使用LEAD()函数的循环查询问题

处理同一ID的日期序列分析

Hey there, let's break down what you've got so far and tweak things to make it more reliable:

原始数据集

Here's your sample data formatted for clarity:

IDdate_INdate_out
11/1/181/2/18
11/3/181/4/18
11/5/181/8/18
21/1/181/5/18
21/7/181/9/18

你执行的SQL语句

SELECT ID, date_IN, Date_out, lead(date_out) over ( partition by (ID) order by ID) as next_out From table

当前查询结果

IDdate_INdate_outnext_out
11/1/181/2/181/4/18
11/3/181/4/181/8/18
11/5/181/8/18Null
21/1/181/5/181/9/18
21/7/181/9/18Null

一个关键优化点

Notice that your ORDER BY ID inside the window function doesn't actually do anything useful—since you're already partitioning by ID, all rows in the partition have the same ID. To ensure the lead() function picks the next chronological record for each ID, you should sort by the check-in or check-out date instead. For example:

SELECT ID, date_IN, Date_out, 
       lead(date_out) over (partition by ID order by date_IN) as next_out 
From table

This guarantees that next_out always corresponds to the subsequent stay's check-out date, regardless of how the data is stored in the table.

You mentioned there are more edge cases in your real data—feel free to share details like overlapping dates, gaps you want to calculate, or specific business logic you're aiming for, and we can refine this further.

内容的提问来源于stack exchange,提问作者a.s.1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:28:01