sql - SQL Server 中的 Over 子句

标签 sql sql-server sql-server-2008 tsql analytic-functions

我有以下查询

select * from 
(
        SELECT distinct 
        rx.patid
       ,rx.fillDate
       ,rx.scriptEndDate
       ,MAX(datediff(day, rx.filldate, rx.scriptenddate)) AS longestScript
       ,rx.drugClass
       ,COUNT(rx.drugName) over(partition by rx.patid,rx.fillDate,rx.drugclass) as distinctFamilies
       FROM [I 3 SCI control].dbo.rx
       where rx.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
       GROUP BY rx.patid, rx.fillDate, rx.scriptEndDate,rx.drugName,rx.drugClass
      
) r
order by distinctFamilies desc

产生的结果看起来像 enter image description here

这应该意味着在表中的两个日期之间 patID 应该有 5 个唯一的药物名称。但是,当我运行以下查询时:

select distinct *
    from rx 
    where patid = 1358801781 and fillDate between '2008-10-17' and '2008-11-16' and drugClass='H4B'

我有一个返回的结果集看起来像

enter image description here

您可以看到,虽然在 2008 年 10 月 17 日和 2009 年 1 月 15 日之间的第二个查询实际上返回了五行,但只有三个唯一名称。我已经尝试过各种修改 over 子句的方法,但都以不同程度的失败告终。如何更改我的查询,以便在为每一行指定的时间范围内只找到唯一 drugName

最佳答案

试一试:

   SELECT DISTINCT
  patid, 
  fillDate, 
  scriptEndDate, 
  MAX(DATEDIFF(day, fillDate, scriptEndDate)) AS longestScript,
  drugClass,
  MAX(rn) OVER(PARTITION BY patid, fillDate, drugClass) as distinctFamilies
FROM (
  SELECT patid, fillDate, scriptEndDate, drugClass,rx.drugName,
  DENSE_RANK() OVER(PARTITION BY patid, fillDate, drugClass ORDER BY drugName) as rn
  FROM [I 3 SCI control].dbo.rx
  WHERE drugClass IN ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
)x
GROUP BY x.patid, x.fillDate, x.scriptEndDate,x.drugName,x.drugClass,x.rn
ORDER BY distinctFamilies DESC

不确定 DISTINCT 是否真的有必要 - 因为您已经使用过,所以保留了它。

关于sql - SQL Server 中的 Over 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14163585/

相关文章:

sql - 如果字段长度大于 5,则获取最后剩余的字符

sql-server - 在 IIS 应用程序上使用集成安全时,Sql 连接失败

sql-server-2008 - SQL 服务器 : concatenating values from two numeric columns

sql-server-2008 - 如何处理ColdFusion存储过程结果中的错误?

SQL 查询连接两个表类似于左外连接

c# - SQL - 是否有更好的方法将用于 where 子句的键列表传递到存储过程中?

sql-server - 在 SQL Server 2012 中解析 XML 数据

sql - 找出一组字母可以组成哪些单词?

python - SQLAlchemy + MySQL 加入奇怪的行为

mysql - 向 MySQL 数据添加前导零