我有我的表(CTE)defintions和結果集here關係部門,在一定的時間範圍內的事件
的CTE可能看起來很奇怪,但它已經過測試,以最有效的方式,我」返回正確的結果還沒找到。以下查詢將查找同時服用兩種或兩種以上藥物的人員ID(patid)的數量。目前,查詢的工作原理是它返回服用兩種藥物的人的藥物標識,但不是同時服用兩種藥物。同時服用兩種藥物的藥物有fillDate
,其中一種藥物落在另一種藥物的scriptEndDate
之前。所以
您可以在此部分結果看到設置在第18行的scriptFillDate
是2009-07-19
這是fillDate
,並從第2行相同patID的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
@RichardTheKiwi固定,查詢我忘了粘貼在這裏。 – wootscootinboogie