教师号  星期号 是否有课
 1    2   有
 1    3   有
 2    1   有
 3    2   有
 1    2   有
写一条sql语句让你变为这样的表
教师号 星期一 星期二 星期三
 1       2   1 
 2   1   
 3       1
各星期下的数字表示:对应的教师在星期几已经排的课数
上面的逻辑怎么实现啊?各位大侠帮帮忙。

解决方案 »

  1.   

    SQL> select 教师号,count(case when 星期号='1' then 是否有课 end) 星期一,
      2  count(case when 星期号='2' then 是否有课 end) 星期二,
      3  count(case when 星期号='3' then 是否有课 end) 星期三,
      4  count(case when 星期号='4' then 是否有课 end) 星期四,
      5  count(case when 星期号='5' then 是否有课 end) 星期五
      6  from kcbp
      7  group by 教师号
      8  order by 教师号
      9  /教师号                   星期一     星期二     星期三     星期四     星期五
    -------------------- ---------- ---------- ---------- ---------- ----------
    1                             0          2          1          0          0
    2                             1          0          0          0          0
    3                             0          1          0          0          0
      

  2.   


    with temp as(
    select 1 tno,2 xh,'有' flag from dual
    union all
    select 1 tno,3 xh,'有' flag from dual
    union all
    select 2 tno,1 xh,'有' flag from dual
    union all
    select 3 tno,2 xh,'有' flag from dual
    union all
    select 1 tno,2 xh,'有' flag from dual
    )
    select tno,sum(decode(xh,1,decode(flag,'有',1,0),null)) 星期一,
                  sum(decode(xh,2,decode(flag,'有',1,0),null)) 星期二,
                  sum(decode(xh,3,decode(flag,'有',1,0),null)) 星期三,
                  sum(decode(xh,4,decode(flag,'有',1,0),null)) 星期四,
                  sum(decode(xh,5,decode(flag,'有',1,0),null)) 星期五,
                  sum(decode(xh,6,decode(flag,'有',1,0),null)) 星期六,
                  sum(decode(xh,7,decode(flag,'有',1,0),null)) 星期七
    from temp group by tno 
      

  3.   


    create table timetable
    (
           tid number,
           weekday number,
           course_flag varchar2(2)
    );insert into timetable values(1,2, '有');
    insert into timetable values(1,3, '有');
    insert into timetable values(2,1, '有');
    insert into timetable values(3,2, '有');
    insert into timetable values(1,2, '有');select tid 教师号,
           -- 如果不想显示 0, 则用null来替换0
           decode(count(decode(weekday, 1, '星期一')), 0,  null, count(decode(weekday, 1, '星期一'))) 星期一,
           count(decode(weekday, 2, '星期二')) 星期二,
           count(decode(weekday, 3, '星期三')) 星期三,
           count(decode(weekday, 4, '星期四')) 星期四,
           count(decode(weekday, 5, '星期五')) 星期五
    from timetable
    group by tid;