我计算患者再入院率,需要找出患者在一定间隔内重新入院的情况,以及频率。我承认数据如下:
Subscriber_id New_Admission_date
01 2016-06-02
02 2016-06-01
03 2016-06-10
04 2016-06-08
02 2016-06-04
02 2016-06-30
03 2016-06-28
为了找到患者在14天内重新入院的内容以及承认之间的间隔时间,我有以下代码:
select ra.Subscriber_id, DATEDIFF(d,ra.first_ad,ra.last_ad) as interval
from
(
select j.Subscriber_ID,
min(j.New_admission_date) as first_ad,
max (j.New_Admission_Date) as last_ad
from June_inpatients as j
inner join
(select j.Subscriber_ID, count(Subscriber_ID) as total
from June_inpatients as j
group by Subscriber_ID
having count(Subscriber_ID) >1 ) as r
on j.Subscriber_ID = r.Subscriber_ID
group by j.Subscriber_ID
) as ra
where DATEDIFF(d,ra.first_ad,ra.last_ad) < 15
问题是某些患者,例如示例数据中的患者ID 02
,有2个以上的患者。我的代码错过了任何中介,因为它使用min()
和max()
。当有三次录取时,我如何找到患者的第一次录取和第二次录取之间的间隔,然后找到第二次录取和第三次录取之间的间隔?
答案 0 :(得分:2)
假设您至少使用SQL 2012,则可以使用Lag功能。
LAG / LEAD的想法是我们可以查询返回的上一行/下一行的数据。
在下面的完整示例中,我使用LAG两次,一次是订阅者,一次是约会。按订户和日期排序可确保前一行/下一行的顺序正确。然后我限制我的where子句以确保:
DECLARE @tbl TABLE (
pkey INT NOT NULL PRIMARY KEY IDENTITY,
subscriber INT NOT NULL,
dt DATETIME NOT NULL
);
INSERT INTO @tbl
( subscriber, dt )
VALUES
( 1, '2016-06-02'),
( 2, '2016-06-01'),
(3, '2016-06-10'),
(4, '2016-06-08'),
(2, '2016-06-04'),
(2, '2016-06-30'),
(3, '2016-06-28');
SELECT *
FROM @tbl
ORDER BY subscriber, dt
; WITH tmp AS (
SELECT subscriber, dt,
LAG(subscriber) OVER (ORDER BY subscriber, dt) previousSubscriber,
LAG(dt) OVER (ORDER BY subscriber, dt) previousDt
FROM @tbl
--ORDER BY subscriber, dt
)
SELECT tmp.*, DATEDIFF(DAY, previousDt, dt)
FROM tmp
WHERE tmp.subscriber = previousSubscriber
AND DATEDIFF(DAY, previousDt, dt) < 15
答案 1 :(得分:1)
如果您使用的是SQL Server 2012或更高版本,请尝试以下操作:
;WITH
cte As
(
SELECT Subscriber_id,
LAG(New_Admission_Date, 1) OVER (PARTITION BY Subscriber_id ORDER BY New_Admission_Date) AS PreviousAdmissionDate,
New_Admission_Date
FROM AdmissionTable
)
SELECT *
FROM cte
WHERE DATEDIFF(DAY, PreviousAdmissionDate, New_Admission_Date) <= 14
答案 2 :(得分:1)
这将在没有滞后功能的情况下工作。
;WITH J
AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY J1.Subscriber_id ORDER BY J1.New_Admission_date ) ROW_ID ,*
FROM June_inpatients J1
)
SELECT J1.Subscriber_id, J1.New_Admission_date Previous_Admission_date ,
J2.Subscriber_id, J2.New_Admission_date , DATEDIFF(DD,J1.New_Admission_date,J2.New_Admission_date) Interval
FROM J J1
INNER JOIN J J2 ON J1.Subscriber_id = J2.Subscriber_id AND J1.ROW_ID = J2.ROW_ID -1
WHERE DATEDIFF(DD,J1.New_Admission_date,J2.New_Admission_date)<15