zoukankan      html  css  js  c++  java
  • 行转列

    student_score表:
    +------+---------+-------+
    | name | subject | score |
    +------+---------+-------+
    | 张三 | 语文 | 78 |
    | 张三 | 数学 | 88 |
    | 张三 | 英语 | 98 |
    | 李四 | 语文 | 89 |
    | 李四 | 数学 | 76 |
    | 李四 | 英语 | 90 |
    | 王五 | 语文 | 89 |
    | 王五 | 数学 | 66 |
    | 王五 | 英语 | 91 |
    +------+---------+-------+

    变换为

    +------+------+------+------+
    | name | 语文 | 数学 | 英语 |
    +------+------+------+------+
    | 张三 | 78 | 88 | 98 |
    | 李四 | 89 | 76 | 90 |
    | 王五 | 89 | 66 | 91 |
    +------+------+------+------+

    方法一:

    --使用decode函数
    select 
    ss.name,
    max(decode(ss.subject,'语文',ss.score)) 语文,
    max(decode(ss.subject,'数学',ss.score)) 数学,
    max(decode(ss.subject,'英语',ss.score)) 英语 
    from student_score ss 
    group by ss.name

    方法二:

    --case when
    select 
    ss.name,
    max(case ss.subject when '语文' then ss.score end) 语文,
    max(case ss.subject when '数学' then ss.score end) 数学,
    max(case ss.subject when '英语' then ss.score end) 英语 
    from student_score ss 
    group by ss.name;

    方法三:

    --left join
    select 
    t1.name,t1.score,t2.score,t3.score 
    from 
    (select name,score from student_score where subject='语文') t1 
    left join 
    (select name,score from student_score where subject='数学') t2 
    on t1.name=t2.name 
    left join 
    (select name,score from student_score where subject='英语') t3 
    on t2.name=t3.name;

    方法四:

    --union all
    select u.name,max(u.yuwen) 语文,max(u.shuxue) 数学,max(u.yingyu) 英语 
    from 
    (
    select name,score yuwen,0 shuxue,0 yingyu from student_score where subject='语文' 
    union all 
    select name,0,score,0 from student_score where subject='数学' 
    union all 
    select name,0,0,score from student_score where subject='英语'
    ) u 
    group by 
    u.name;
  • 相关阅读:
    关于在MyEclipse中页面中文乱码的问题
    如何用Navicat for MySQL 将mysql中的数据库导出,导入。
    淘宝链接池的配置
    c3p0配置
    人生规划
    spring问题: Unable to validate using XSD: Your JAXP provider
    List数组和Set集合
    Tomcat6内存不足问题及解决方法
    清华校长送给毕业生的五句话
    个人图文理解类的封装
  • 原文地址:https://www.cnblogs.com/staff/p/13467049.html
Copyright © 2011-2022 走看看