首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在一定时间范围内对事件进行关系划分

在一定时间范围内对事件进行关系划分
EN

Stack Overflow用户
提问于 2012-12-13 22:11:09
回答 1查看 78关注 0票数 0

我有我的表定义和结果集这里

CTE看起来可能很奇怪,但它已经过测试,并以我所发现的最有效的方式返回了正确的结果。下面的查询将查找同时服用两种或两种以上药物的人ID (patid)的数量,同时使用。目前,该查询的工作范围是返回服用两种药物的人的patID,但不能同时返回两种药物。服用这两种药物的标志是一种药物的一个fillDate下降到另一种药物的scriptEndDate之前。所以

您可以在这个部分结果集中看到,在第18行中,scriptFillDate2009-07-19,它位于第2行中相同的patID的fillDatescriptEndDate之间。我需要添加什么约束来过滤这些不需要的结果?

代码语言:javascript
复制
--PatientDrugList is a CTE because eventually parameters might be passed to it
--to alter the selection population
;with PatientDrugList(patid, filldate, scriptEndDate,drugName,strength)
as
(
    select rx.patid,rx.fillDate,rx.scriptEndDate,rx.drugName,rx.strength
        from rx
),
--the row constructor here will eventually be parameters for a stored procedure
DrugList (drugName)
as
(
    select x.drugName
        from (values ('concerta'),('fentanyl'))
        as x(drugName)
        where x.drugName is not null
)


    --the row number here is so that I can find the largest date range
    --(the largest datediff means the person was on a given drug for a larger
    --amount of time.  obviously not a optimal solution
     --celko inspired relational division!
     select distinct row_number() over(partition by pd.patid, drugname order by datediff(day,pd.fillDate,pd.scriptEndDate)desc)  as rn
     ,pd.patid
    ,pd.drugname
    ,pd.fillDate
    ,pd.scriptEndDate
    from PatientDrugList as pd
    where not exists
    (select * from DrugList 
    where not exists
    (select * from PatientDrugList as pd2
    where(pd.patid=pd2.patid)
    and (pd2.drugName = DrugList.drugName)))
    and exists 
    (select * 
        from DrugList
        where DrugList.drugName=pd.drugName
    )
    group by pd.patid, pd.drugName,pd.filldate,pd.scriptEndDate
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-13 22:22:55

为了性能、查询计划和结果的稳定性,将原始查询包装到CTE中,或者更好地将其存储在临时表中。

下面的查询(假设CTE选项)将为您提供两种药物服用时的重叠时间。

代码语言:javascript
复制
;with tmp as (
   .. your query producing the columns shown ..
)
select *
  from tmp a
  join tmp b on a.patid = b.patid and a.drugname <> b.drugname
 where a.filldate < b.scriptenddate
   and b.filldate < a.scriptenddate;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13869395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档