下面的查询基于一个复杂的视图,该视图按我的意愿工作(我不打算包含该视图,因为我认为它不会帮助解决手头的问题)。我不能正确的是drugCountsinFamilies
专栏。我需要它来显示distinct drugName
每个药物家族的 s 数量。您可以从第一个屏幕截图中看到有三个不同的 H3A 行。对于drugCountsInFamilies
H3A 应该是 3(有三种不同的 H3A 药物。)
您可以从第二个屏幕截图中看到,drugCountsInFamilies
第一个屏幕截图中的内容是捕获列出药物名称的行数。
以下是我的问题,对不正确的部分进行了评论
select distinct
rx.patid
,d2.fillDate
,d2.scriptEndDate
,rx.drugName
,rx.drugClass
--the line directly below is the one that I can't figure out why it's wrong
,COUNT(rx.drugClass) over(partition by rx.patid,rx.drugclass,rx.drugname) as drugCountsInFamilies
from
(
select
ROW_NUMBER() over(partition by d.patid order by d.patid,d.uniquedrugsintimeframe desc) as rn
,d.patid
,d.fillDate
,d.scriptEndDate
,d.uniqueDrugsInTimeFrame
from DrugsPerTimeFrame as d
)d2
inner join rx on rx.patid = d2.patid
inner join DrugTable as dt on dt.drugClass=rx.drugClass
where d2.rn=1 and rx.fillDate between d2.fillDate and d2.scriptEndDate
and dt.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
order by rx.patid
如果我尝试在count(rx.drugClass)
子句中添加不同的内容,SSMS 会发疯。可以使用窗口函数来完成吗?