2016-09-10 82 views
1

我目前的工作在高校管理項目,我想計算出每棟樓的能力的個體之和時的情況是每個部門可以容納不同的部分像下面(CoMP的情況下在同一建築物內選出) 我寫了一個查詢在那裏我得到的容量總和,這是不必要的 我的查詢是:如何計算所選列

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 | 
+----------+-------------+----------+ 

回答

0

因爲只需要檢查存在於department表建築物的能力,你需要爲每個buildingcapacity計算總和,並添加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 
+0

tysm工作就像一個魅力:) ..明白我懷疑 – minigeek

+0

考慮[接受一個答案(http://meta.stackexchange.com/questions/5234/如何接受答案 - 如果你覺得有幫助的話)。 –

+0

如何做到這一點..我是新登錄和聲譽是不是太多upvote :( – minigeek

-1

使用下面的查詢:

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

如果你想確保至少有1部在該建築物然後使用inner join

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

TY爲先回答但第二個查詢顯示錯誤的輸出:) – minigeek

+0

對不起,我錯誤地打開在哪裏。看我的編輯。 –

+0

仍表現出相同的output..anyways烏爾答不參加作品:) – minigeek