【问题标题】:How to compare multiple columns, on multiple rows - comparison only applicable within rows who hold common ID如何在多行上比较多列 - 比较仅适用于持有共同 ID 的行
【发布时间】:2020-05-22 19:50:50
【问题描述】:

表中的每条记录都有一个course_id(自增),一个study_id(指一个病人,每个病人在这个表中可以有多个记录),每条记录包含一个start_date和一个stop_date。

我希望在每个患者的记录中进行比较,看看这些日期范围是否有重叠。但是,我想为该表中的所有患者执行此操作。

例如:

course_id  study_id  start_date  stop_date

1234123    12222     01/09/2019  01/12/2019
1444233    12222     01/10/2019  01/01/2020  

想要的查询结果:

study_id

12222

所有在开始/停止日期有类似重叠的 study_ids 等等。

希望至少有人能引导我朝着正确的方向前进。谢谢!

【问题讨论】:

  • 请以表格文本的形式提供示例数据和预期结果。
  • 供您参考,this 是一个完整构造的问题的样子。有关用于改进问题的提示和工具,这里有一篇很好的参考文章。 How to post a SQL question on a public forum
  • @GMB - 感谢您的提示 - 新来的!

标签: sql date ms-access


【解决方案1】:

我认为这可以满足您的要求:

select distinct study_id
from mytable t
where exists (
    select 1 
    from mytable t1
    where 
        t1.course_id <> t.course_id
        and t1.study_id = t.study_id
        and t1.start_date <= t.end_date
        and t1.end_date   >= t.start_date
)

这通过使用具有exists 条件的相关子查询来工作,该条件过滤具有相同study_id 和重叠日期范围的另一条记录的记录。然后,外部查询使用distinct 删除重复的study_id

【讨论】:

    【解决方案2】:

    使用自加入

    select distinct t.study_id
    from yourtable t
    join yourtable t2 on t.study_id = t2.study_id
      and t.course_id > t2.course_id
      and t.start_date <= t2.stop_date
      and t2.start_date <= t.stop_date
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2015-11-15
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 2016-12-15
      • 2016-07-16
      相关资源
      最近更新 更多