sql - 带有患者的sql查询
问题描述
在数据库查询方面需要帮助;
patients(cpr(key), firstname, sirname, address, postalnumber, country, journal)
allergies(allergens(key)), allergytype, allergic_reaction)
patientallergies(allergens(key), cpr(key))
我们如何将对完全相同的过敏原过敏的患者成对地写出 CPR 数字?CPR 号码只能打印一次,CPR 号码不能与自身配对。
我们目前的建议是这样的:
SELECT p1.cpr, p2.cpr
FROM patients p1, patients p2
不知道从这里去哪里
解决方案
一种方法是自联接和聚合。这使用窗口函数来计算每位患者的过敏原数量,以确保匹配准确:
with pa as (
select pa.*, count(*) over (partition by cpr) as cnt
from patientallergies pa
)
select pa.cpr, pa2.cpr
from pa join
pa pa2
on pa.allergan = pa2.allergan and pa.cnt = pa2.cnt
group by pa.cpr, pa2.cpr, pa.cnt
having count(*) = pa.cnt;