如何编写 SQL 查询来循环多个表或使用递归查询

问题描述 投票:0回答:1

当我在 tmp_lookup 中有 1 个项目时,我的结果很好。当我在查找表中有 1 + 项时,结果与预期不符,有一些重复记录。 “Tmp_pat1”表为 person_id 和 Concept_id 的组合创建记录,我将其加入 tmp_pat_km_format 表中,并且我们使用 tmp_pat1 中的概念名称来填充 tmp_pat_freq 表中是否缺少它们。

现在的问题是,由于每个 person_id、concept_id 组合都有两条记录,因此两条记录都被添加。如果我一次可以做 1 个 Conceptid 就可以了。因此,如果我做一个循环并一次查看一个概念 id,它就会起作用。我需要合并结果。

例如,第一个循环在 tmp_lookup 中只有泼尼松,并且我们仅使用 tmp_pat_freq 中具有该概念 id 的记录。第二个循环含有阿莫西林。那么结果表将是两个 tmp_pat_km_format 的并集。 我知道循环在 sql 中并不常见。这就是为什么我认为必须有更好的方法来做到这一点,也许是递归查询,但我被困住了。

select distinct concept_id, concept_name from tmp_lookup ;

--1551099 泼尼松

--1713332 阿莫西林

Drop table if exists tmp_pat1;
create temp table tmp_pat1 as                       
select a.person_id, b.* from tmp_pat a join (select  distinct concept_id, concept_name from tmp_lookup ) b on 1 = 1;

Drop table if exists tmp_pat_km_format;
create temp table tmp_pat_km_format as
  select
  ROW_NUMBER() Over() as id2
  ,a.grp
  ,a.gender
  ,a.age_group
  ,c.w_numpat*1.000/c.u_numpat as weight
  ,case when d.concept_name is not null then d.concept_name else e.concept_name end as concept_name
  ,case when b.days_to_first_visit is not null then b.days_to_first_visit else a.followup_days_observed end as days_observed
  ,case when b.days_to_first_visit is not null then 1 else 0 end as had_event
  ,case when num_baseline_dates = 0 then 1 else 0 end as naive_pat
  from
  tmp_pat a
  left join (select * from tmp_pat_freq where visit_type = 'All') b on a.person_id = b.person_id
  left join tmp_pat_weights c on a.age = c.age and a.gender = c.gender and a.grp = c.grp
  left join (select distinct concept_id,concept_name from tmp_lookup) d on b.concept_id = d.concept_id
  left join tmp_pat1 e on a.person_id = e.person_id;
sql loops window-functions recursive-query
1个回答
0
投票

我在这里看到了一大堆危险信号。 Joel Coehoorn 在评论中提到,如果您想在 SQL 中执行循环,那么您就做错了。我注意到您正在创建一个“临时”表,它实际上只是另一个表。它不使用本地、全局或变量表,它将像任何其他 SQL 表一样出现在您的数据库中。如果这个脚本有任何并发运行的机会,你可能会遇到一些非常混乱的问题。

但是,你并不是在要求对你所做的事情进行批评。您可以使用游标在 SQL 中创建循环。我对于是否建议将此作为解决方案犹豫不决,因为它们几乎总是一个糟糕的选择,会导致缩放和性能问题,就像没人管的事一样。不过,如果您尝试在 SQL 中循环,游标可以做到这一点。已警告您。

如果您像考虑命令式编程语言一样思考 SQL,那么您就误解了它的工作原理。SQL 更多的是围绕集合论设计的,您关心的是集合中的包含或排除,而不是集合的构建方式。

© www.soinside.com 2019 - 2024. All rights reserved.