SQL - 查找特定日期之后的两个最接近的日期
SQL - Find the two closest date after a specific date
亲爱的 Stack Overflow 社区,
我正在寻找 患者 ID,其中第一个日期之后的两个连续日期少于 7 天。
所以第 2 天和第 1 天之间的差异 date <= 7
天
以及第 3 天和第 2 date <= 7
天之间的差异
示例:
ID Date
1 9/8/2014
1 9/9/2014
1 9/10/2014
2 5/31/2014
2 7/20/2014
2 9/8/2014
对于患者1,其后的两个日期相隔不到7天。
然而,对于患者 2,接下来的日期相隔超过 7 天(50 天)。
我正在尝试编写一个只输出患者 ID“1”的 SQL 查询。
感谢您的帮助:)
您可以尝试使用 window 函数 lag()
select * from
(
select id,date,lag(date) over(order by date) as prevdate
from tablename
)A where datediff(day,date,prevdate)<=7
您想使用 lead()
,但这很复杂,因为您只希望在前三行使用它。我想我会选择:
select t.*
from (select t.*,
lead(date, 1) over (partition by id order by date) as next_date,
lead(date, 2) over (partition by id order by date) as next_date_2,
row_number() over (partition by id order by date) as seqnum
from t
) t
where seqnum = 1 and
next_date <= date + interval '7' day and
next_date2 <= next_date + interval '7' day;
亲爱的 Stack Overflow 社区,
我正在寻找 患者 ID,其中第一个日期之后的两个连续日期少于 7 天。
所以第 2 天和第 1 天之间的差异 date <= 7
天
以及第 3 天和第 2 date <= 7
天之间的差异
示例:
ID Date
1 9/8/2014
1 9/9/2014
1 9/10/2014
2 5/31/2014
2 7/20/2014
2 9/8/2014
对于患者1,其后的两个日期相隔不到7天。
然而,对于患者 2,接下来的日期相隔超过 7 天(50 天)。
我正在尝试编写一个只输出患者 ID“1”的 SQL 查询。
感谢您的帮助:)
您可以尝试使用 window 函数 lag()
select * from
(
select id,date,lag(date) over(order by date) as prevdate
from tablename
)A where datediff(day,date,prevdate)<=7
您想使用 lead()
,但这很复杂,因为您只希望在前三行使用它。我想我会选择:
select t.*
from (select t.*,
lead(date, 1) over (partition by id order by date) as next_date,
lead(date, 2) over (partition by id order by date) as next_date_2,
row_number() over (partition by id order by date) as seqnum
from t
) t
where seqnum = 1 and
next_date <= date + interval '7' day and
next_date2 <= next_date + interval '7' day;