简体   繁体   English

如何在SQL中的滚动日期范围内标识记录的MIN值

[英]How to identify MIN value for records within a rolling date range in SQL

I am trying to calculate a MIN date by Patient_ID for each record in my dataset that dynamically references the last 30 days from the date (Discharge_Dt) on that row. 我正在尝试通过Patient_ID为我的数据集中的每条记录计算一个MIN日期,该记录动态引用该行中从日期(Discharge_Dt)开始的最后30天。 My initial thought was to use a window function, but I opted for a subquery, which is close, but not quite what I need. 我最初的想法是使用窗口函数,但我选择了一个子查询,该子查询很近,但并不是我所需要的。

Please note, my sample query is also missing logic that limits the MIN Discharge_Dt to the last 30 days, in other words, I do not want a MIN Discharge_Dt that is older than 30 days for any given row. 请注意,我的示例查询也缺少将MIN Discharge_Dt限制为最近30天的逻辑,换句话说,我不希望任何给定行的MIN Discharge_Dt都超过30天。

Sample Query: 查询样例:

SELECT Patient_ID,
       Discharge_Dt,

      /* Calculating the MIN Discharge_Dt by Patient_ID for the last 30 
         days based upon the Discharge_Dt for that row */

      (SELECT MIN(Discharge_Dt)
       FROM admissions_ds AS b
       WHERE a.Patient_ID = b.Patient_ID AND
             a.Discharge_Dt >= DATEADD('D', -30, GETDATE())) AS MIN_Dt

FROM admissions_ds AS a

Desired Output Table: 所需的输出表:

Patient_ID | Discharge_Dt | MIN_Dt      
10         | 2017-08-15   | 2017-08-15         
10         | 2017-08-31   | 2017-08-15          
10         | 2017-09-21   | 2017-08-31          
15         | 2017-07-01   | 2017-07-01         
15         | 2017-07-18   | 2017-07-01               
20         | 2017-05-05   | 2017-05-05          
25         | 2017-09-24   | 2017-09-24  

Here you go, Just a simple join required. 在这里,只需一个简单的联接即可。

drop TABLE if EXISTS admissions_ds;
create table admissions_ds (Patient_ID int,Discharge_Dt date);
insert into admissions_ds
values
  (10,'2017-08-15'),
  (10,'2017-08-31'),
  (10,'2017-09-21'),
  (15,'2017-07-01'),
  (15,'2017-07-18'),
  (20,'2017-05-05'),
  (25,'2017-09-24');

select t1.Patient_ID,t1.Discharge_Dt,min(t2.Discharge_Dt) as min_dt
from admissions_ds as t1
join admissions_ds as t2 on t1.Patient_ID=t2.Patient_ID and t2.Discharge_Dt > t1.Discharge_Dt - interval '30 days'
group by 1,2
order by 1,2
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM