有2张表,班级表A,学生生活补贴表B(所有班级学生在一起,学生有班级id),现在要根据班级id查询到 班级名称和这个班级所有学生的生活补贴,我是这样写的:
select a.name ,sum(b.money) over( order by  b.classId) 
from A a,B b
where 
a.classId = 1 and b.classId = 1现在的问题是:学生生活补贴表B可能没有这个班级id为 1 的人的补贴记录,也就是select sum(b.money) over( order by  b.classId)  from B b where b.classId = 1 结果为空值,但是我想要查询到的班级名称仍然显示在结果里,没有补贴就默认为0,该如何写?我像下面这样写也不行:
select a.name  from a where a.classId = 1 union all select sum(b.money) over( order by  b.classId)  from B b where b.classId = 1 

解决方案 »

  1.   


    select a.name ,nvl(sum(b.money) over( order by b.classId),0)
    from A a left join B b on a.classid=b.classid
    where  a.classId = 1
    group by a.name
      

  2.   

    with a as(
    select 1 id,'a' name from dual
    union all
    select 2 id,'b' name from dual
    union all
    select 3 id,'c' name from dual
    ),b as(
    select 1 id,'张三' name, 10 money from dual
    union all
    select 1 id,'李四' name, 12 money from dual
    union all
    select 3 id,'王五' name, 13 money from dual
    )
    select a.name,nvl(sum(money),0) from a,b where a.id = b.id(+) group by a.name
      

  3.   


    select a.name ,sum(b.money) over( order by b.classId)  
    from A a,B b
    where  
    a.classId=b.classId(+)