我有我的表定义和结果集这里
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发布于 2012-12-13 22:22:55
为了性能、查询计划和结果的稳定性,将原始查询包装到CTE中,或者更好地将其存储在临时表中。
下面的查询(假设CTE选项)将为您提供两种药物服用时的重叠时间。
;with tmp as (
.. your query producing the columns shown ..
)
select *
from tmp a
join tmp b on a.patid = b.patid and a.drugname <> b.drugname
where a.filldate < b.scriptenddate
and b.filldate < a.scriptenddate;https://stackoverflow.com/questions/13869395
复制相似问题