您的位置:首页 > 博客中心 > 数据库 >

数据库 行转列 列转行详解

时间:2022-03-10 17:10

create table TEST_TB_GRADE   

  1. [sql] view plaincopy
  1. create table TEST_TB_GRADE  
  2.   ID        NUMBER(10) not null,  
  3.   COURSE    VARCHAR2(20 CHAR),  
  4. )  

select t.user_name,   

  1. [sql] view plaincopy
  1. select t.user_name,  
  2.   sum(decode(t.course, ‘数学‘, score,null)) as MATH,  
  3. from test_tb_grade t  
  4. order by t.user_name  
 

select t2.SCORE_GP,   

  1. [sql] view plaincopy
    1. select t2.SCORE_GP,  
    2.   sum(decode(t2.course, ‘数学‘, COUNTNUM,null)) as MATH,  
    3. from (  
    4.          case when t.score  <60 then ‘00-60‘  
    5.               when t.score >=80 then ‘80-100‘ end as SCORE_GP,  
    6.   FROM test_tb_grade t  
    7.         case when t.score  <60  then ‘00-60‘  
    8.               when t.score >=80 then ‘80-100‘ end  
    9. group by t2.SCORE_GP  
    10. create table TEST_TB_GRADE2   
      1. [sql] view plaincopy
        1. create table TEST_TB_GRADE2  
        2.   ID         NUMBER(10) not null,  
        3.   CN_SCORE   FLOAT,  
        4.   EN_SCORE   FLOAT  
        5. select user_name, ‘语文‘ COURSE , CN_SCORE as SCORE from test_tb_grade2    

          1. [sql] view plaincopy
            1. select user_name, ‘语文‘ COURSE , CN_SCORE as SCORE from test_tb_grade2   
            2. union select user_name, ‘英语‘ COURSE, EN_SCORE as SCORE from test_tb_grade2   
            3. create table TEST_TB_GRADE3     
              1. [sql] view plaincopy
                1. create table TEST_TB_GRADE3    
                2.       USER_NAME VARCHAR2(20 CHAR),    
                3.       SCORE     FLOAT    
                4. insert all  
                  1. [sql] view plaincopy
                    1. insert all  
                    2. into test_tb_grade3(USER_NAME,COURSE,SCORE) values(user_name, ‘数学‘, MATH_SCORE)  
                    3. select user_name, CN_SCORE, MATH_SCORE, EN_SCORE from test_tb_grade2;  
                    4. commit;  

                     别忘记commit操作,然后再查询TEST_TB_GRADE3,发现表中的数据就是列转成行了。

                     

                     

                    本文连接:http://sjsky.iteye.com/blog/1152167


                    来源: <http://blog.csdn.net/mezheng/article/details/7426765>
                     

                    来自为知笔记(Wiz)


                    数据库 行转列 列转行详解,布布扣,bubuko.com

                    热门排行

                    今日推荐

                    热门手游