【发布时间】:2017-01-25 10:14:42
【问题描述】:
我的数据库中有两个表:
Building(bno,address,bname) - PK is bno. bno
Room(bno,rno,floor,maxstud) - PK is bno,rno (together)
Building 表代表建筑物编号、地址和名称。 Room 表代表楼号、房间号、楼层号和最多可入住的学生人数。
我要写的查询:
找到一栋至少有 10 个房间的建筑物,最多可以住 1 个学生。列应该是 bno, bname, number of such rooms.
我写的:
select building.bno, building.bname, count(rno)
from room natural join building
where maxstud =1
group by bno, bname
having count(rno)>=10
我的解决方案是什么:
with temp as (
select bno, count(distinct rno) as sumrooms
from room
where maxstud=1
group by bno
)
select bno, bname, sumrooms
from building natural join temp
where sumrooms>=10
我的解决方案正确吗?我没有看到使用子查询的理由,但现在恐怕我错了。
谢谢,
艾伦
【问题讨论】:
-
我认为您的解决方案不会编译,因为您没有在 group by 子句中包含每个未聚合的列。
-
@KamilG。你是对的,谢谢!
标签: sql postgresql subquery common-table-expression