给定一个数据库模式:students(rollno int, hostel int, parent_inc int),选择在宿舍拥有最大父母收入的学生的rollno, hostel no, parent_inc的最佳方法是什么?
我编写了以下查询:
SELECT rollno, hostel,parent_inc
FROM students
WHERE parent_inc IN (select max(parent_inc) from students group by hostel);然而,这有一个问题。
在一个例子中,如果。第9招待所学生的parent_inc是x(比如说)和最大值。parent_inc在第8招待所的学生中是y(比如说),其中(y>x)。
现在,巧合的是,如果第8招待所有一个学生也有父母公司x,那么上面的查询也会显示,除了显示父母收入x和y的第8和第9宿舍的学生名册外,这是不正确的。
有谁能帮我解决这件事吗?
发布于 2020-09-26 04:55:29
希望这是你想要的。对于外部选择中的每一行,您应该将其parent_inc值与内部选择中相同的宿舍(仅)的max(parent_inc)值进行比较。在内部选择中使用where子句。可以使用别名引用内部选择中的外部行。
with students as (
select *
from
(values (1, 1, 100000),
(2, 1, 50000),
(3, 2, 200000),
(4, 2, 250000)
) t (rollno, hostel, parent_inc)
)
select *
from students s
where
s.parent_inc = (select max(parent_inc) from students ss where ss.hostel = s.hostel)发布于 2020-09-26 13:23:20
如果您只想要一行,那么使用order by和fetch (或您的数据库的等效值):
SELECT rollno, hostel, parent_inc
FROM students
ORDER BY parent_inc DESC
FETCH FIRST 1 ROW ONLY;https://stackoverflow.com/questions/64073907
复制相似问题