有如下表:
CREATE table score_rows(sname VARCHAR(50),class VARCHAR(50),chinese TINYINT,math TINYINT,english TINYINT);
INSERT into score_rows VALUES('a','二一班',70,80,90);
INSERT into score_rows VALUES('b','二一班',75,85,95);
INSERT into score_rows VALUES('c','二二班',70,90,90);
INSERT into score_rows VALUES('d','二三班',80,80,90);
INSERT into score_rows VALUES('e','三一班',90,80,90);
INSERT into score_rows VALUES('f','三二班',80,70,90);
INSERT into score_rows VALUES('g','三三班',90,80,90);
目标:以下实现方式不够灵活:(select sname,class,'chinese' as type,chinese as sore from score_rows) 
union   
(select sname,class,'math' as type,math as sore from score_rows)  
union   
(select sname,class,'english' as type,english as sore from score_rows)  请问有什么比较灵活的方式,可以在有课程数不固定的情况下实现?

解决方案 »

  1.   


    课程数不固定的,这种只能用动态sql来实现
      

  2.   

    UNPIVOT  列转行
      

  3.   

    如果用MYSQL怎么实现?
      

  4.   

    有:表A:学生表
    学号   姓名  班级  ....
      1        a       一班
      2        b      二班
    ...................表B:科目表
    科目ID  科目名称
       1            chinese
      2              english
     3               math
    ..................表C:学习表对应哪个学生要学哪门课程
    学号            科目ID
     1                    1
     1                     2
     1                    3
    2                    1
    2                    2
    2                   3
    。表D: 成绩表
    学号     科目号     成绩
      1            1            70
      1            2              80
      1            3             90
      2             1          60
     2              2          100
     2             3           90
    .......这样一来,想要什么样的格式的数据都可以搞出来。而且科目可以任意加。
      

  5.   


    比如要想查询学生的成绩:
    SELECT A.ID, A.NAME, C.NAME AS KM, D.SCORE FROM A LEFT JOIN D on A.XH=D.XH LEFT JOIN C on D.KM=C.KM;
      

  6.   

    use tempdb;
    DROP table IF EXISTS score_rows;
    CREATE table score_rows(sname VARCHAR(50),class VARCHAR(50),chinese TINYINT,math TINYINT,english TINYINT);
    INSERT into score_rows VALUES('a','二一班',70,80,90);
    INSERT into score_rows VALUES('b','二一班',75,85,95);
    INSERT into score_rows VALUES('c','二二班',70,90,90);
    INSERT into score_rows VALUES('d','二三班',80,80,90);
    INSERT into score_rows VALUES('e','三一班',90,80,90);
    INSERT into score_rows VALUES('f','三二班',80,70,90);
    INSERT into score_rows VALUES('g','三三班',90,80,90);select group_concat('select sname, class,', quote(column_name), ' as type,', column_name, ' as sore from score_rows' separator ' union ')
    into @sql
    from information_schema.columns
    where table_schema=database() and table_name='score_rows'
    and column_name not in('sname', 'class');
    prepare st from @sql;
    execute st;
    deallocate prepare st;
      

  7.   

    那个@sql能接收的长度是不是有限制?我的列太多,@sql并没有接收完全部的列