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

时间:2016-09-10 14:00:28

标签: mysql

我目前正在从事大学管理项目,我希望计算每个建筑物的容量,当每个部门的案例可以容纳不同的部分如下(comp和选择在同一建筑物内) 我写了一个查询,我得到的总容量是不需要的 我的疑问是:

select sum(distinct capacity) 
from classroom  
where building in (select building from department group by building)

我得到的是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 |
+----------+-------------+----------+

2 个答案:

答案 0 :(得分:0)

由于您只想检查department表格中存在的建筑物容量,因此每个building需要计算capacity之和,并添加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

如果您只需要department中不存在建筑物的容量,那么请删除exists子句:

select
  building, sum(capacity) as capacity
from classrom
group by building

答案 1 :(得分:-1)

使用以下查询:

SELECT building, SUM(capacity) as total_capacity
FROM classroom 
GROUP BY building;

如果您想确保该建筑物中至少有一个部门,请使用inner join

SELECT classroom.building, SUM(capacity) as total_capacity
FROM classroom 
INNER JOIN department 
  ON classroom.building == department.building 
GROUP BY classroom.building;