【问题标题】:SQL - count with or without subquery?SQL - 计算有或没有子查询?
【发布时间】: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


【解决方案1】:

你的解决方案更好。

如果您不确定,请在示例数据集上运行这两个查询,并说服自己结果是相同的。

【讨论】:

  • 感谢您的回答!
【解决方案2】:

您的查询将执行得更快,但恐怕无法编译,因为您没有在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2012-06-28
    相关资源
    最近更新 更多