select ID,TERM,score as china from cloud2012 where subject='china'
union all
select ID,TERM,score as math from cloud2012 where subject='math' 
union all
select ID,TERM,score as english from cloud2012 where subject='english'
  请问怎么行列合并,我想使用这种方法进行行列转换。
  在存储过程中如何写转换的SQL。

解决方案 »

  1.   

    ID       TERM      SUBJECT      SCORE
    001     2009        CHINA            77
    001     2009        MATH             71
    001     2009        ENGLISH         80id       TERM    CHINA      ENGLISH  MATH  
    001    2009      77              80            71
     请问怎么用union all  进行转换?
      

  2.   


    SQL> with t as(
      2       select '001' id,'2009' term,'china' subject,77 score from dual union all
      3       select '001','2009','math',71 from dual union all
      4       select '001','2009','english',80 from dual)
      5  select id,term,
      6         max(case subject when 'china' then score end) china,
      7         max(case subject when 'math' then score end) math,
      8         max(case subject when 'english' then score end) english
      9  from t
     10  group by id,term;ID  TERM      CHINA       MATH    ENGLISH
    --- ---- ---------- ---------- ----------
    001 2009         77         71         80
      

  3.   

    select id,term,
    sum(decode (subject,'china',score,o)) china,
    sum(decode (subject, 'math',score,0)) math,
    sum(decode (subject,'english'score,0)) english
    from table_name
    group by id,term
      

  4.   

    楼上正解,不过有人说Union all 也可以,只是我不太了解
      

  5.   

    select id,term,
               max(case subject when 'china' then score end) china,
               max(case subject when 'math' then score end) math,
              max(case subject when 'english' then score end) english
        from a
       group by id,term;