MySQL ——group by子句使用with rollup

     group by 子句使用with rollup关键字之后,具有分组加和的功能。即:在所有的分组记录之后,自动新增一条记录,从全局计算所有记录的数据。

0 问题描述

   求出每年的学生平均成绩,及历史至今的平均成绩,结果保留两位小数。

1 数据准备

create table rollup_test
(
  name varchar(8)   COMMENT'',
  year int COMMENT'',
  score int COMMENT''
)CHARACTER SET utf8 COLLATE utf8_general_ci;

insert into rollup_test
values ('a',2016, 85),
       ('b',2016, 45),
       ('c',2016, 90),
       ('a',2015, 75),
       ('b',2015, 90);

2 数据分析

  完成代码如下:

select `year`,
        round(avg(score) ,2) as avg_score
from rollup_test group by `year`
union all
select '历史至今' as `year`,
       round(avg(score) ,2) as avg_score
from rollup_test

方式二:利用group by with rollup 替换union all进行简化

select `year`,
        round(avg(score) ,2) as avg_score
from rollup_test
group by `year`
with rollup

由输出结果可知,with rollup 会自动新增一条记录:

year   avg_score
null      77.00

结果与下列代码等价

select  '历史至今' as `year`,
           round(avg(score) ,2) as avg_score
from rollup_test

再借助函数ifnull 或 coalesce() 空字段赋值

上述代码继续优化为:

select  coalesce (`year`,'历史至今') as `year`,
        round(avg(score) ,2) as avg_score
from rollup_test
group by `year`
with rollup

 输出结果为:

3 小结

相关推荐

  1. MySQL WHERE子句使用和优化方法

    2024-02-10 05:16:01       32 阅读
  2. SQL使用WITH ROLLUP子句计算每个分组的合计值

    2024-02-10 05:16:01       63 阅读
  3. SQLite Glob 子句

    2024-02-10 05:16:01       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-10 05:16:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-10 05:16:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-10 05:16:01       87 阅读
  4. Python语言-面向对象

    2024-02-10 05:16:01       96 阅读

热门阅读

  1. 聊聊PowerJob的任务调度

    2024-02-10 05:16:01       37 阅读
  2. C语言——oj刷题——字符串左旋

    2024-02-10 05:16:01       41 阅读
  3. 学习Android的第九天

    2024-02-10 05:16:01       46 阅读
  4. Mysql报错:too many connections

    2024-02-10 05:16:01       49 阅读
  5. 什么是集群服务器

    2024-02-10 05:16:01       55 阅读
  6. Linux中的numactl命令指南

    2024-02-10 05:16:01       47 阅读