将复杂的SQL查询解构为多个查询和联接

时间:2018-06-22 20:14:02

标签: sql-server tsql

有人可以帮助将这个复杂的SQL查询分解为各个步骤吗?我正在尝试建立多个表并加入这个感觉很不透明的多步查询。谢谢!

select 
    visit_date, 
    count(vo1.visit_id) as num_visits,
    sum(case when co1.person_id is not null then 1 else 0 end) as num_visits_w_cond
from 
    visit_occurrence vo1
left join
    (select distinct 
         person_id, visit_id, condition_date
     from 
         condition_occurrence
     where 
         condition_id = 12345)) co1 on vo1.person_id = co1.person_id
                                    and vo1.visit_date = co1.condition_date
                                    and vo1.visit_id = co1.visit_id
where 
    visit_id = 1234
group by 
    visit_date
order by 
    visit_date;

理想情况下,我想在中间步骤中生成一些数据表,然后在最后加入并计数,但是不确定这是什么样子。

编辑:谢谢您的评论。关于各个表的清晰度:

  1. 第一个选择将在visit_occurrence表中查询与visit_id#匹配“ 1234”的所有visit_id,并为所有访问返回不同的person_id,visit_date和visit_id。因此,person_id,visit_date,visit_id元组是唯一的,即,具有不同visit_date或不同visit_id的同一person_id不符合重复条件。只有相同的元组才是重复的。

  2. 第二个选择将查询condition_occurrence表以查找与condition_id#12345相匹配的所有condition_id,并返回不同的person_id,visit_id和condition_date。因此person_id,visit_id,condition_date元组是唯一的,即具有不同visit_id或condition_date的同一个person_id不是重复项。只有相同的元组才是重复的。

  3. 在person_id上合并表1和表2,visit_date = condition_date,visit_id = visit_id。然后计算每个日期有多少不同的person_id。

  4. 在表1中,计算每个日期与多少个visit_id相关联。

希望这更清楚吗?再次感谢您的反馈。

1 个答案:

答案 0 :(得分:1)

我怀疑这样做的效果会更好,但是与您的要求接近。我会远离临时表(这是我根据您的问题得出的结论)。

with cteVO as --common table expression for visit_occurrence
(
    select distinct person_id, visit_date, visit_id
    from visit_occurrence
    where visit_id = 1234
),
cteCO as -- common table expression for condition_occurrence
(
    select distinct person_id, visit_id, condition_date
    from condition_occurrence 
    where condition_id = 12345
)
-- Join both CTEs to get the count of person_id and count of visit_id
SELECT cteVO.visit_date, COUNT(cteVO.person_id) AS count_person_id,
    COUNT(cteVO.visit_id) AS count_visit_id
FROM cteVO
INNER JOIN cteCO ON cteVO.person_id = cteCO.person_id 
    AND cteVO.visit_date = cteCO.condition_date
    AND cteVO.visit_id = cteCO.visit_id
GROUP BY cteVO.visit_date