首页 > 解决方案 > 如何找到每个病房最高的病人

问题描述

我有两张桌子:

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) 

我不明白子查询,请有人解释一下。谢谢

标签: sql

解决方案


奇怪的答案。我会选择更直接的:

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频率较低。


推荐阅读