sql - 如何找到每个病房最高的病人
问题描述
我有两张桌子:
patient (patient_id (PK), patient_name, gender, height, weight, staff_no, ward_no)
ward (ward_no (PK), ward_name, number_of_beds)
我想找到每个病房里最高的病人。
这是我的查询:
Select patient_name, MAX(height) from patient Group By patient_name
这个查询有效吗?
这是一个模拟考试问题,所以我有模型答案。
select patient_name
from patient p1
where not exists (select * from patient p2 where p1.ward_no = p2.ward_no and p1.height < p2 .height)
我不明白子查询,请有人解释一下。谢谢
解决方案
奇怪的答案。我会选择更直接的:
select p.patient_name
from patient p
where p.height = (select max(p2.height)
from patient p2
where p2.ward_no = p.ward_no
) ;
相关子查询正在获取给定患者病房中所有患者的最大高度。然后,它会返回与此高度匹配的所有患者。
你的版本正在做类似的事情。就是说“病房里没有更高的病人”。有时,这all
在考试中使用:
select p.patient_name
from patient p
where p.height >= all (select p2.height
from patient p2
where p2.ward_no = p.ward_no
) ;
在实践中,any
使用all
频率较低。
推荐阅读
- firebase - 如何在作为列表存储在 Firestore 字段中时为键具有唯一值
- swift - 在 Xcode 项目中本地添加 Swift 包依赖
- python - Keras中的词袋嵌入层?
- python - 如何在 Peewee 中使用历史记录表进行版本控制?
- c++ - 为什么不调用继承类的析构函数?
- flutter - 在颤动中获取弧的路径长度
- javascript - 2 个相等变量之间的比较在 Google 脚本(表格)中返回 false
- python - 在类内的默认参数中使用 functools.partial 时的令人惊讶的行为
- excel - 需要有关将 CSV 文件导出到自定义地图的帮助
- laravel - 如何在 laravel php 中从数据库中获取印地语文本,