zoukankan      html  css  js  c++  java
  • Mysql进阶

    如图一,通过sq了实现图二:

    图一如下:

    图二如下:

    附建表语句&初始化数据语句:

    CREATE TABLE `sc` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `user_name` varchar(32) NOT NULL DEFAULT '',
      `subject` varchar(32) NOT NULL DEFAULT '',
      `score` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    insert into sc(id,user_name,subject,score) 
    values (1,"张三","语文",80),(2,"张三","数学",90),(3,"张三","英语",70),(4,"张三","生物",85),
           (5,"李四","语文",80),(6,"李四","数学",90),(7,"李四","英语",70),(8,"李四","生物",85);

    以下有简单易懂的&万能通用的两种写法:

     1.简单易懂的一种写法,由于一名学生一门课只有一个分数,所以下面sql中max函数完全可以换为sum等其他聚合函数。

    select `user_name`,
        max(case `subject` when '语文' then IFNULL(`score`, 0) else 0 end) as '语文',
        max(case `subject` when '数学' then IFNULL(`score`, 0) else 0 end) as '数学',
        max(case `subject` when '英语' then IFNULL(`score`, 0) else 0 end) as '英语',
        max(case `subject` when '生物' then IFNULL(`score`, 0) else 0 end) as '生物'
    from `sc`
    group by `user_name`;

    运行结果:

    2.不需要提前知道有多少门课程,动态生成列,万能通用的一种写法。

    set @splice_sql = null;
    SELECT 
        GROUP_CONCAT(DISTINCT
            CONCAT('max(if(subject=''',subject,''', score, 0)) as ''',subject, ''''))
        into @splice_sql
    from sc;
    
    set @splice_sql = CONCAT('select user_name,', @splice_sql, ' from sc group by user_name');
    prepare bella_test from @splice_sql;
    execute bella_test;
    DEALLOCATE prepare bella_test;

    运行结果

  • 相关阅读:
    博客园装修行动—我设计的新首页
    按作者名称查看评论
    [新功能]通过RSS阅读收藏夹
    [公告]首页小调整
    时间的格式化
    [公告]将读书心得区改成技术书评区
    [汇报]昨天晚上博客园的程序又出现了问题
    [公告]博客园已经成功迁移至新服务器
    [好消息]博客园乔迁新居
    [公告]博客园程序升级
  • 原文地址:https://www.cnblogs.com/mjtabu/p/12558826.html
Copyright © 2011-2022 走看看