3

我有以下查询

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

产生的结果看起来像 在此处输入图像描述

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

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

我返回的结果集看起来像

在此处输入图像描述

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

4

1 回答 1

3

试一试:

   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 是否真的有必要 - 因为你已经使用它了。

于 2013-01-04T20:40:03.240 回答