sql - 计算不同记录的窗口函数

标签 sql sql-server-2008 tsql

下面的查询基于一个复杂的 View ,并且该 View 按我的意愿工作(我不打算包含该 View ,因为我认为它不会帮助解决手头的问题)。我不能正确的是drugCountsinFamilies柱子。我需要它来显示 distinct drugName 的号码s 为每个药物家族。您可以从第一个屏幕截图中看到有三个不同的 H3A 行。 drugCountsInFamilies对于 H3A 应该是 3(有三种不同的 H3A 药物。)

enter image description here

您可以从第二个屏幕截图中看到正在发生的事情是 drugCountsInFamilies在第一个屏幕截图中,正在捕获列出药物名称的行数。
enter image description here

以下是我的问题,对不正确的部分进行了评论

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两个ASCDESC在要计算的列上:

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/

相关文章:

php - Insert Ignore - 有没有办法知道语句是否被忽略?数据库

php - "Order by desc"倒序?

sql - T-SQL查找字符字符串并获取表达式右侧的所有字符

sql - 每特定时间选择一行

sql - SQL 中的 SELECT 语句中的 EXEC

SQL 2008 - 结果集顺序问题

c# - SQL 表中的搜索结果

sql-server - 如何在存储过程中执行动态SQL?

sql-server-2008 - T-SQL 查看子查询Where 子句

c# - Entity Framework 连接字符串 utf8