StuInfo 表
  stuID(PK)   stuName
  1          王五
  2           李四
  3          张三
...ScoreINfo表
ID(PK) stu_ID(FK) score   subject
 1       1              34     数学
 2       1              56     语文
 3       1              36     外语
 4       2              78     数学
 5       2              98     语文
 6       2              45     外语
.....
要求结果如下:
select stuID 编号,stuName 姓名
,(select score from ScoreInfo ss where subject ='语文'and ss.stu_ID =stu.stuID ) 语文
,(select score from ScoreInfo ss where subject ='数学'and ss.stu_ID =stu.stuID ) 数学
,(select score from ScoreInfo ss where subject ='外语'and ss.stu_ID =stu.stuID ) 外语
from StuInfo stu
inner join ScoreInfo  on stuID = stu_ID
group by stuID,stuName;   
  
编号     姓名      数学     语文     外语
1 张三 34 56 36
2 李四 78 98 45
3 王五 NULL NULL NULL
  高手看能不能有更好的方法来解决.... 谢谢. 

解决方案 »

  1.   

    with a as (select '1' stuID, '王五' stuName   from dual
                union
               select '2' stuID, '李四' stuName   from dual 
    ),
         b as (
         select 1 ID, 1 stu_ID, 34 score, '数学' subject   from dual
         union
        select 2 ID, 1 stu_ID, 35 score, '数学2' subject   from dual
        union
        select 3 ID, 1 stu_ID, 36 score, '数学3' subject   from dual
        union
        select 4 ID, 2 stu_ID, 34 score, '数学' subject   from dual
         )
    select b.stu_ID,max(a.stuName),sum(decode(b.subject,'数学',b.score,null)) s1,
          sum(decode(b.subject,'数学2',b.score,null)) s2,
          sum(decode(b.subject,'数学3',b.score,null)) s3from a,b
    where a.stuID = b.stu_ID
    group by b.stu_ID
      

  2.   

    where a.stuID = b.stu_ID->where a.stuID = b.stu_ID(+)