2012-08-06 43 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