Oracle中不同表和多表连接的两个不同列(添加)的总和

use*_*132 3 sql sum oracle11g

我有三张桌子.

学校:学号(PK),年份,学校名称.
注册:学校代码,年份,种姓,c1,c2,c3,c4,c5,c6,c7,c8
CLASS:schoolcode,year,classid,rooms

现在,我想找到1至4级入学的学校名单和1-4班使用的教室数量(CLASSID定义为:1级和2级为7级,3级和4级为8级,9级为 - 5和6,10对于7级和8级;并且种姓被定义为1为一般,2为sc,3为st,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 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(7,8) and 
      e.caste in(1,2,3,4) 
group by m.schoolcode, m.schoolname 
Run Code Online (Sandbox Code Playgroud)

但结果显示不正确.入学率远高于实际入学率,同样适用于教室.

Nik*_*vić 6

好的,试试这个,看看你的问题是否因重复加入记录而产生:

select m.schoolcode, m.schoolname, e_sum, c_sum 
  from dise2k_master m
 inner join
 (
    select schoolcode,
           sum(c1 + c2 + c3 + c4) e_sum
      from dise2k_enrolment09
     where year='2011-12'
       and caste in(1,2,3,4) 
     group by schoolcode
 ) e
    on m.schoolcode=e.schoolcode
 inner join
 (
    select schoolcode,
           sum(rooms) c_sum
      from dise2k_clsbycondition
     where year='2011-12'
       and classid in(7,8)
     group by schoolcode
 ) c
    on m.schoolcode=c.schoolcode
 where m.year='2011-12'
Run Code Online (Sandbox Code Playgroud)