我在这里有我的表 (cte) 定义和结果集
CTE 可能看起来很奇怪,但它已经过测试并以我发现的最有效的方式返回正确的结果。下面的查询将找到同时服用两种或多种药物的人员 ID(patid)的数量。目前,该查询只返回服用两种药物的人的 patID,但不能同时返回两种药物。服用这两种药物是由一种fillDate
药物中的一种在另一种药物之前下降来表示的scriptEndDate
。所以
您可以在这个部分结果集中看到,在第 18 行,scriptFillDate
它2009-07-19
位于第 2 行中相同 patID 的fillDate
和之间scriptEndDate
。我需要添加什么约束才能过滤这些不需要的结果?
--PatientDrugList is a CTE because eventually parameters might be passed to it
--to alter the selection population
;with PatientDrugList(patid, filldate, scriptEndDate,drugName,strength)
as
(
select rx.patid,rx.fillDate,rx.scriptEndDate,rx.drugName,rx.strength
from rx
),
--the row constructor here will eventually be parameters for a stored procedure
DrugList (drugName)
as
(
select x.drugName
from (values ('concerta'),('fentanyl'))
as x(drugName)
where x.drugName is not null
)
--the row number here is so that I can find the largest date range
--(the largest datediff means the person was on a given drug for a larger
--amount of time. obviously not a optimal solution
--celko inspired relational division!
select distinct row_number() over(partition by pd.patid, drugname order by datediff(day,pd.fillDate,pd.scriptEndDate)desc) as rn
,pd.patid
,pd.drugname
,pd.fillDate
,pd.scriptEndDate
from PatientDrugList as pd
where not exists
(select * from DrugList
where not exists
(select * from PatientDrugList as pd2
where(pd.patid=pd2.patid)
and (pd2.drugName = DrugList.drugName)))
and exists
(select *
from DrugList
where DrugList.drugName=pd.drugName
)
group by pd.patid, pd.drugName,pd.filldate,pd.scriptEndDate