Mysql 如何计算所选列的单个和

Mysql 如何计算所选列的单个和,mysql,Mysql,我目前正在大学管理项目中工作,我想计算每栋建筑的容量,如果每个部门可以在同一栋建筑中容纳不同的部分,如下面的comp和elect 我写了一个查询,在那里我得到了不需要的总容量 我的问题是: select sum(distinct capacity) from classroom where building in (select building from department group by building) 我得到的ans是660!! 在这个嵌套查询中,我是否在错误的位置使用了s

我目前正在大学管理项目中工作,我想计算每栋建筑的容量,如果每个部门可以在同一栋建筑中容纳不同的部分,如下面的comp和elect 我写了一个查询,在那里我得到了不需要的总容量 我的问题是:

select sum(distinct capacity) 
from classroom  
where building in (select building from department group by building)
我得到的ans是660!! 在这个嵌套查询中,我是否在错误的位置使用了sum和distinct?如何获得单个建筑的容量

department
+------------+----------+-----------+
| dept_name  | building | budget    |
+------------+----------+-----------+
| Biology    | Watson   |  90000.00 |
| Comp. Sci. | Taylor   | 100000.00 |
| Elec. Eng. | Taylor   |  85000.00 |
| Finance    | Painter  | 120000.00 |
| History    | Painter  |  50000.00 |
| Music      | Packard  |  80000.00 |
| Physics    | Watson   |  70000.00 |
+------------+----------+-----------+    
classroom
+----------+-------------+----------+
| building | room_number | capacity |
+----------+-------------+----------+
| Packard  | 101         |      500 |
| Painter  | 514         |       10 |
| Taylor   | 3128        |       70 |
| Watson   | 100         |       30 |
| Watson   | 120         |       50 |
+----------+-------------+----------+
使用以下查询:

SELECT building, SUM(capacity) as total_capacity
FROM classroom 
GROUP BY building;
如果要确保该建筑中至少有一个部门,请使用内部连接


由于您只想检查部门表中存在的建筑物的容量,因此需要为每个建筑物计算容量总和,并添加exists子句,以仅显示至少一套公寓的居住建筑物:

select
  building, sum(capacity) as capacity
from classrom c
where exists (
  select 1
  from department d
  where c.building = d.building
  )
group by building
如果您只需要容量,而不管部门中是否存在建筑,则删除exists子句:


第一个答案是ty,但第二个查询显示了错误的输出:仍然显示相同的输出..不管怎样,没有连接的ans工作:考虑是否有帮助。如何做。。我是新加入的,声誉也没什么可提升的:
select
  building, sum(capacity) as capacity
from classrom c
where exists (
  select 1
  from department d
  where c.building = d.building
  )
group by building
select
  building, sum(capacity) as capacity
from classrom
group by building