3
我有產生的結果看起來像 在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'
我有一個結果集返回,看起來像
你可以看到,雖然在事實上五行返回第二個查詢在2008年10月17日和2009年1月15日之間,只有三個獨特的名字。我嘗試過修改over子句的各種方法,所有方法都有不同級別的非成功。如何更改我的查詢,以便在每行指定的時間範圍內只發現唯一drugName
?
請解釋你的第二個查詢與你的第一個查詢的關係。並請擴展你的問題「我如何改變我的查詢...」 - 你需要選擇其他哪些列以及drugName,以及如何確定哪些clmid(例如)應該與每個唯一的drugName一起顯示? (我假設你不想要簡單的東西,比如「從rx中選擇不同的drugName,其中patid = xxx .....」) –
第二個查詢與第一個查詢相關,因爲它是表中的ACTUAL數據。您可以看到第二個查詢中有五行。這五行對應於第一個屏幕截圖中的「distinctFamilies」列。但是,您可以看到,實際上只有三種獨特的藥物名稱。 – wootscootinboogie
如果你在oracle上count(distinct fieldname1)over(partition by fieldname2)'可以解決你的問題。但是sqlserver8會給你一個'count(distinct fieldname)'的錯誤,所以你必須在這裏嘗試一種不同的方法。 – Saju