sql - 找出重叠 er 数据库中的总人数
问题描述
我试图找到:
- 非患者的医生总数
- 非医生的患者总数
- 既是患者又是医生的总人数
我似乎无法得到正确的答案。
SQL:
CREATE TABLE persons (
id integer primary key,
name text
);
CREATE TABLE doctors (
id integer primary key,
type text,
FOREIGN KEY (id) REFERENCES persons(id)
);
CREATE TABLE patients (
id integer primary key,
suffering_from text,
FOREIGN KEY (id) REFERENCES persons(id)
);
INSERT INTO persons (id, name) VALUES
(1, 'bob'), (2, 'james'), (3, 'bill'), (4, 'mark'), (5, 'chloe');
INSERT INTO doctors (id, type) VALUES
(2, 'family doctor'), (3, 'eye doctor'), (5, 'family doctor');
INSERT INTO patients (id, suffering_from) VALUES
(1, 'flu'), (2, 'diabetes');
选择语句:
select count(d.id) as total_doctors, count(pa.id) as total_patients, count(d.id) + count(pa.id) as both_doctor_and_patient
from persons p
JOIN doctors d
ON p.id = d.id
JOIN patients pa
ON p.id = pa.id;
解决方案
一种选择使用left join
s frompersons
和条件聚合:
select
count(dr.id) filter(where pa.id is null) cnt_doctor_not_patient,
count(pa.id) filter(where dr.id is null) cnt_patient_not_doctor,
count(pa.id) filter(where do.id is not null) cnt_patient_and_doctor,
count(*) filter(where dr.id is null and pa.id is null) cnt_persons_not_dotor_nor_patient
from persons pe
left join doctors dr on dr.id = pe.id
left join patients pa on pa.id = pe.id
作为奖励,这使您有机会计算既不是病人也不是医生的人。如果您不需要该信息,则 afull join
更简单,并且不需要带persons
表:
select
count(dr.id) filter(where pa.id is null) cnt_doctor_not_patient,
count(pa.id) filter(where dr.id is null) cnt_patient_not_doctor,
count(pa.id) filter(where dr.id is not null) cnt_patient_and_doctor
from doctors dr
full join patients pa using (id)
推荐阅读
- sql - 基于公共元素 SQL Server 组合整数对
- android - 如何在android上创建永久后台服务
- windows - 捕获当前分支名称并在 Windows 上使用 Git 别名将其删除?
- node.js - 导出为 ES6 模块
- express - Express.js 无法使用 express.static 显示目录“images”中的图像
- python - 物体之间的部分碰撞
- linux - 使用expect打开一个新终端并在终端中运行命令
- macos - 核心图形的基本事件处理
- javascript - 使用 PHP 和 jQuery 显示目录中的文件
- python - 朴素贝叶斯分类问题 - ValueError:域数学错误