我有以下查询
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 子句的方法,但都具有不同程度的不成功。如何更改我的查询,以便仅在为每一行指定的时间范围内找到唯一的 s? drugName