2013-01-04 77 views
3

我有產生的結果看起來像 enter image description here在SQL Server中第

以下查詢

select * from 
(
     SELECT distinct 
     rx.patid 
     ,rx.fillDate 
     ,rx.scriptEndDate 
     ,MAX(datediff(day, rx.filldate, rx.scriptenddate)) AS longestScript 
     ,rx.drugClass 
     ,COUNT(rx.drugName) over(partition by rx.patid,rx.fillDate,rx.drugclass) as distinctFamilies 
     FROM [I 3 SCI control].dbo.rx 
     where rx.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e') 
     GROUP BY rx.patid, rx.fillDate, rx.scriptEndDate,rx.drugName,rx.drugClass 

) r 
order by distinctFamilies desc 

這應該意味着在表中兩個日期之間的patID應該有5獨特的藥物名稱。然而,當我運行以下查詢:

select distinct * 
    from rx 
    where patid = 1358801781 and fillDate between '2008-10-17' and '2008-11-16' and drugClass='H4B' 

我有一個結果集返回,看起來像

enter image description here

你可以看到,雖然在事實上五行返回第二個查詢在2008年10月17日和2009年1月15日之間,只有三個獨特的名字。我嘗試過修改over子句的各種方法,所有方法都有不同級別的非成功。如何更改我的查詢,以便在每行指定的時間範圍內只發現唯一drugName

+0

請解釋你的第二個查詢與你的第一個查詢的關係。並請擴展你的問題「我如何改變我的查詢...」 - 你需要選擇其他哪些列以及drugName,以及如何確定哪些clmid(例如)應該與每個唯一的drugName一起顯示? (我假設你不想要簡單的東西,比如「從rx中選擇不同的drugName,其中patid = xxx .....」) –

+0

第二個查詢與第一個查詢相關,因爲它是表中的ACTUAL數據。您可以看到第二個查詢中有五行。這五行對應於第一個屏幕截圖中的「distinctFamilies」列。但是,您可以看到,實際上只有三種獨特的藥物名稱。 – wootscootinboogie

+0

如果你在oracle上count(distinct fieldname1)over(partition by fieldname2)'可以解決你的問題。但是sqlserver8會給你一個'count(distinct fieldname)'的錯誤,所以你必須在這裏嘗試一種不同的方法。 – Saju

回答

3

拍攝一個鏡頭吧:

SELECT DISTINCT 
    patid, 
    fillDate, 
    scriptEndDate, 
    MAX(DATEDIFF(day, fillDate, scriptEndDate)) AS longestScript, 
    drugClass, 
    MAX(rn) OVER(PARTITION BY patid, fillDate, drugClass) as distinctFamilies 
FROM (
    SELECT patid, fillDate, scriptEndDate, drugClass,rx.drugName, 
    DENSE_RANK() OVER(PARTITION BY patid, fillDate, drugClass ORDER BY drugName) as rn 
    FROM [I 3 SCI control].dbo.rx 
    WHERE drugClass IN ('h3a','h6h','h4b','h2f','h2s','j7c','h2e') 
)x 
GROUP BY x.patid, x.fillDate, x.scriptEndDate,x.drugName,x.drugClass,x.rn 
ORDER BY distinctFamilies DESC 

不知道DISTINCT是真的有必要 - 它留在你既然已經用它。