【问题标题】:SQL - Find the two closest date after a specific dateSQL - 查找特定日期之后的两个最接近的日期
【发布时间】:2018-11-14 12:35:43
【问题描述】:

尊敬的 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 查询。

感谢您的帮助:)

【问题讨论】:

  • 我认为你应该在这个时候展示你拥有的代码。
  • 如果给定 id 的行数超过三行怎么办?
  • 很遗憾,当我写这篇文章时,我没有工作代码。我不知道如何像 python 或 C# 一样在 SQL 中建立索引。

标签: sql amazon-athena presto


【解决方案1】:

您想使用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;

【讨论】:

  • 谢谢@Gordon,这似乎是我需要的。引导功能运行良好!我实际上使用了函数lead,其中有一个参数,即lead(date, 1) 和lead(date, 2) 来获取第一个日期和第二个日期。
  • @Vinci 。 . .很好的收获。
【解决方案2】:

您可以尝试使用窗口函数 lag()

select * from
(
select id,date,lag(date) over(order by date) as prevdate
from tablename
)A where datediff(day,date,prevdate)<=7

【讨论】:

    猜你喜欢
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2013-02-05
    • 1970-01-01
    • 2021-01-01
    • 2017-04-22
    • 1970-01-01
    相关资源
    最近更新 更多