sql – 用于计算不同记录的窗口函数

前端之家收集整理的这篇文章主要介绍了sql – 用于计算不同记录的窗口函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的查询基于一个复杂的视图,视图按照我的意愿工作(我不会包含视图,因为我认为它不会对手头的问题有所帮助).我无法做到的是drugCountsinFamilies专栏.我需要它来向我展示每个药物家族的不同药物名称数量.您可以从第一个screencap看到有三个不同的H3A行. H3A的药物家族应该是3(有三种不同的H3A药物.)

您可以从第二个屏幕截图中看到,第一个屏幕截图中的drugCountsInFamilies正在捕获药物名称列出的行数.

以下是我的问题,评论部分不正确

  1. select distinct
  2. rx.patid,d2.fillDate,d2.scriptEndDate,rx.drugName,rx.drugClass
  3. --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
  4. from
  5. (
  6. select
  7. ROW_NUMBER() over(partition by d.patid order by d.patid,d.uniquedrugsintimeframe desc) as rn,d.patid,d.fillDate,d.scriptEndDate,d.uniqueDrugsInTimeFrame
  8. from DrugsPerTimeFrame as d
  9. )d2
  10. inner join rx on rx.patid = d2.patid
  11. inner join DrugTable as dt on dt.drugClass=rx.drugClass
  12. where d2.rn=1 and rx.fillDate between d2.fillDate and d2.scriptEndDate
  13. and dt.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
  14. order by rx.patid

如果我尝试在count(rx.drugClass)子句中添加一个distinct,SSMS就会生气.可以使用窗口函数完成吗?

解决方法

将计数(不同)作为Windows函数需要一个技巧.实际上有几个级别的技巧.

因为您的请求实际上非常简单 – 值始终为1,因为rx.drugClass位于分区子句中 – 我将做出假设.假设您想要计算每个独特药物类别的数量.

如果是这样,请执行由patid和drugClass分区的row_number().当这是1,在一个patid中,然后一个新的drugClass开始.创建一个在这种情况下为1的标志,在所有其他情况下为0.

然后,您可以简单地使用分区子句进行求和以获取不同值的数量.

查询(格式化之后我可以阅读它),如下所示:

  1. select rx.patid,rx.drugClass,SUM(IsFirstRowInGroup) over (partition by rx.patid) as NumDrugCount
  2. from (select distinct rx.patid,(case when 1 = ROW_NUMBER() over (partition by rx.drugClass,rx.patid order by (select NULL))
  3. then 1 else 0
  4. end) as IsFirstRowInGroup
  5. from (select ROW_NUMBER() over(partition by d.patid order by d.patid,d.uniqueDrugsInTimeFrame
  6. from DrugsPerTimeFrame as d
  7. ) d2 inner join
  8. rx
  9. on rx.patid = d2.patid inner join
  10. DrugTable dt
  11. on dt.drugClass = rx.drugClass
  12. where d2.rn=1 and rx.fillDate between d2.fillDate and d2.scriptEndDate and
  13. dt.drugClass in ('h3a','h2e')
  14. ) t
  15. order by patid

猜你在找的MsSQL相关文章