2012-12-13 47 views
0

我有我的表(CTE)defintions和結果集here關係部門,在一定的時間範圍內的事件

的CTE可能看起來很奇怪,但它已經過測試,以最有效的方式,我」返回正確的結果還沒找到。以下查詢將查找同時服用兩種或兩種以上藥物的人員ID(patid)的數量。目前,查詢的工作原理是它返回服用兩種藥物的人的藥物標識,但不是同時服用兩種藥物。同時服用兩種藥物的藥物有fillDate,其中一種藥物落在另一種藥物的scriptEndDate之前。所以 enter image description here

您可以在此部分結果看到設置在第18行的scriptFillDate2009-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 
+0

@RichardTheKiwi固定,查詢我忘了粘貼在這裏。 – wootscootinboogie

回答

1

將原始查詢包裝到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; 
+0

+1當我沒有提供我寫的實際查詢時能夠回答問題。我試圖自己加入CTE,並且一直在犯錯誤。歡呼Kiwi先生:) – wootscootinboogie