--学生表
create table test1(
 id number(19),
 name varchar(16)
);insert into test1(id ,name ) values (1,'张三');
insert into test1(id ,name ) values (2,'李四');
insert into test1(id ,name ) values (3,'王五'); --课程表
create table test2(
 id number(19),
 name varchar(16)
);insert into test2(id ,name ) values (1,'数学');
insert into test2(id ,name ) values (2,'语文');
insert into test2(id ,name ) values (3,'英语');--选课表
create table test3(
 userid number(19),
 classid number(19)
);insert into test3(userid ,classid ) values (1,1);
insert into test3(userid ,classid ) values (1,2);
insert into test3(userid ,classid ) values (1,3);
insert into test3(userid ,classid ) values (2,1);
insert into test3(userid ,classid ) values (2,2);结果:
  userid        username          classname
    1               张三           数学 语文 英语
    2               李四           数学 语文
    3               王五           没有选课   

解决方案 »

  1.   


    select userid, username, nvl(wmsys.wm_concat(classname), '没有选课')
      from (select a.id userid, a.name username, b.name classname
              from test1 a, test2 b, test3 c
             where a.id = c.userid(+)
               and b.id(+) = c.classid)
     group by userid, username;
      

  2.   

    又是一个涉及行转列的问题 最近这方面的问题挺多啊 版主可以发个专贴介绍一下
    简单说明一下这种问题的解决思路
    如果课程固定 可以用decode一个一个罗列出来
    select g.stuname,max(decode(g.subject, '大学物理', g.grade, NULL)) as 大学物理,max(decode(g.subject, '大学英语', g.grade, NULL)) as 大学英语 from mw_app.mwt_gradeinfo g group by g.stuname
    如果列数不固定 就要用存储过程
    我是这么解决的 在存储过程中用游标把所有课程查询出来,然后拼sql,然后创建视图 create view as sql
    存储过程执行完 就select * from viewname 来查询
    不知道还有没有更好的办法
      

  3.   

    刚才没有看清题目 如果想把选的课放到一个字段 用wm_concat函数就可以 1楼正解
      

  4.   


    SQL> select userid,username,nvl(replace(wmsys.wm_concat(classname),',',' '), '没有选课')
      2    from (select userid, username, classname, rownum rn
      3            from (select distinct a.id userid, a.name username, b.name classname
      4                    from test1 a, test2 b, test3 c
      5                   where a.id = c.userid(+)
      6                     and b.id(+) = c.classid
      7                  )
      8         )
      9  group by userid, username;
     
     
                  USERID USERNAME         CLASSNAME
    -------------------- ---------------- --------------------------------------------------------------------------------
                       1 张三             数学 英语 语文
                       2 李四             数学 语文
                       3 王五             没有选课