下面的查询基于一个复杂的 View ,并且该 View 按我的意愿工作(我不打算包含该 View ,因为我认为它不会帮助解决手头的问题)。我不能正确的是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 会发疯条款。可以使用窗口函数来完成吗?
最佳答案
我遇到了这个问题,以寻找解决我计算不同值的问题的方法。在寻找答案时,我遇到了这个 post .见最后一条评论。我已经对其进行了测试并使用了 SQL。它对我来说非常有效,我想我会在这里提供另一种解决方案。
总之,使用 DENSE_RANK()
, 与 PARTITION BY
分组的列和 ORDER BY
两个ASC
和 DESC
在要计算的列上:
DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName ASC) +
DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName DESC) - 1 AS drugCountsInFamilies
我用这个作为自己的模板。
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields ASC ) +
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields DESC) - 1 AS DistinctCount
我希望这有帮助!
关于sql - 计算不同记录的窗口函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13480880/