【发布时间】:2012-11-08 23:21:36
【问题描述】:
下面的查询基于一个复杂的视图,并且该视图按我的意愿工作(我不打算包含该视图,因为我认为它不会帮助解决手头的问题)。我不能正确的是drugCountsinFamilies 列。我需要它来显示每个药物家族的distinct drugNames 数量。您可以从第一个屏幕截图中看到有三个不同的 H3A 行。 H3A 的drugCountsInFamilies 应该是 3(有三种不同的 H3A 药物。)
您可以从第二个屏幕截图中看到,第一个屏幕截图中的 drugCountsInFamilies 正在捕获列出药物名称的行数。
以下是我的问题,cmets 在不正确的部分
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 会发疯。可以用窗口函数来完成吗?
【问题讨论】:
-
@littlebobbytables 我无法使用
count(distinct rx.drugClass) over(partition by...)而不出现错误。 -
@LittleBobbyTables 不起作用,因为我需要两个
different同一类药物。如果同一个 drugName 列了两次,也是同一个类,但是我需要算一次。 -
您的请求没有意义,因为您在分区子句中有 rx.drugClass。因此,
count(distinct rx.drugClass)将始终返回 1。 -
我不认为这是正确的,但我在阳光下尝试了一切明智的分区,让它给我正确的答案。我可能最终只使用派生表,但我希望我能以这种方式解决它。
标签: sql sql-server-2008 tsql