2012-08-06 46 views
0

我有三個表。Oracle SQL加11g中的多表加入查詢

  1. SCHOOL:schoolcode(PK),year,schoolname。
  2. ENROLMENT:schoolcode,一年,類名,招收
  3. CLASS:schoolcode,今年的classid,客房

現在,我想找到的學校名單,在類名報名 - 1至4以及1-4級使用的教室數量。

我用下面的查詢:

select 
    m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from 
    dise2k_enrolment09 e, dise2k_master m, dise2k_clsbycondition 
where 
    m.schoolcode = e.schoolcode 
    and m.schoolcode = c.schoolcode 
    and e.year = '2011-12' and m.year = '2011-12' and c.year = '2011-12' 
    and classid in (1,2,3,4) 
    and e.classname in (1,2,3,4) 
group by 
    m.schoolcode, m.schoolname 

但結果顯示不正確。在課堂上,入學人數遠遠高於實際人數。

回答

0

試試這個:

select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from dise2k_enrolment09 e join dise2k_master m 
on m.schoolcode=e.schoolcode 
join dise2k_clsbycondition c 
on m.schoolcode=c.schoolcode 
where e.year='2011-12' and m.year='2011-12' and c.year='2011-12' 
and classid in(1,2,3,4) 
and e.classname in(1,2,3,4) 
group by m.schoolcode, m.schoolname 
+0

號和類名是CLASSID不一樣的東西。它是一個例子。對不起,它是我的錯,我無法向你解釋我的問題。實際上,classname的值爲1至8,但classid的值爲7,8,9,10(1,2級爲7,8級3,4級,9級爲5,6級,10級爲7,8級) )。現在你能幫我找到答案。因爲上述兩個答案都行不通。 – user1579132 2012-08-07 06:28:15

+0

編號Classname和classid不是一回事。它是一個例子。對不起,它是我的錯,我無法向你解釋我的問題。實際上,classname的值爲1至8,但classid的值爲7,8,9,10(1,2級爲7,8級3,4級,9級爲5,6級,10級爲7,8級) )。我在(7,8)中寫到了classid。現在你能幫我找到答案。因爲上述兩個答案都行不通。 – user1579132 2012-08-07 07:38:55

1

試試這個:

select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from dise2k_enrolment09 e, dise2k_master m ,dise2k_clsbycondition c 
where m.schoolcode=e.schoolcode and m.schoolcode=c.schoolcode and e.year='2011-12' and m.year='2011-12' and c.year='2011-12' 
and c.classid in(1,2,3,4) 
and e.classname = c.classid 
group by m.schoolcode, m.schoolname 

的方式,你就會明白:and e.classname in(1,2,3,4)是喜歡你的where子句在具有OR操作。

(c.classid=1 or c.classid=2 or c.classid=3 or c.classid=4) 
and 
(e.classname=1 or e.classname=2 or e.classname=3 or e.classname=4) 

所以,c.classid可以是「1」,e.classname可以是「2」,這是錯誤的

UPDATE我仍然認爲問題是,你不連接c.classide.classname

試試這樣說:

select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from dise2k_enrolment09 e, dise2k_master m ,dise2k_clsbycondition c 
where m.schoolcode=e.schoolcode and m.schoolcode=c.schoolcode and e.year='2011-12' and m.year='2011-12' and c.year='2011-12' 
and c.classid in(1,2,3,4) 
and c.classid = decode(e.classname,1,7,2,7,3,8,4,8,5,9,6,9,7,10,8,10) 
group by m.schoolcode, m.schoolname 
+0

編號Classname和classid不是一回事。它是一個例子。對不起,它是我的錯,我無法向你解釋我的問題。實際上,classname的值爲1至8,但classid的值爲7,8,9,10(1,2級爲7,8級3,4級,9級爲5,6級,10級爲7,8級) )。我在(7,8)中寫了classid。現在你能幫我找到答案。因爲上述兩個答案都行不通。 – user1579132 2012-08-07 07:39:40