SQL计数是否包含子查询?

SQL计数是否包含子查询?,sql,postgresql,subquery,common-table-expression,Sql,Postgresql,Subquery,Common Table Expression,我的数据库中有两个表: Building(bno,address,bname) - PK is bno. bno Room(bno,rno,floor,maxstud) - PK is bno,rno (together) 建筑表代表建筑编号、地址和名称。 房间表代表建筑物编号、房间编号、楼层编号和可居住在房间内的最大学生人数 我必须写的查询: 找一栋至少有10个房间的建筑,最多可以住1个房间。列应为bno、bname、此类房间的数量 我写的是: select building.bno, bu

我的数据库中有两个表:

Building(bno,address,bname) - PK is bno. bno
Room(bno,rno,floor,maxstud) - PK is bno,rno (together)
建筑表代表建筑编号、地址和名称。 房间表代表建筑物编号、房间编号、楼层编号和可居住在房间内的最大学生人数

我必须写的查询:

找一栋至少有10个房间的建筑,最多可以住1个房间。列应为bno、bname、此类房间的数量

我写的是:

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子句中包含所有未聚合的列(此处:
building.bname

此外,您拥有的解决方案(不是您的解决方案)会计算不同的房间号,因此您可能会得出结论,一栋建筑可以有多个房间具有相同的编号,例如在不同的楼层,因此可以通过唯一的三元组
(bno,rno,floor)
正确识别一个房间

考虑到我在上面写的内容,您的查询看起来:

select building.bno, building.bname, count(distinct rno)
from room natural join building
where maxstud = 1
group by 1,2 -- I used positions here, you can use names if you wish
having count(distinct rno) >= 10

谢谢你的回答!我认为您的解决方案不会编译,因为您没有在GROUPBY子句中包含所有未聚合的列。@KamilG。你说得对,谢谢!