文章目录
前言
本文主要记录SQL-在查询结果后加入多行新的数据或者其他查询结果的相关笔记,主要用到的函数有union/union all/with rollup。
1. 对多个查找结果进行并集操作
table1表中有id和num两列数据,现有两行值分别为(1,3)、(2,6)
1、 union
对多个查找结果进行并集操作,不包括重复行。
select * from table1
union
select * from table1
输出结果:
2、 union all
对多个查找结果进行并集操作,包括重复行。
select * from table1
union all
select * from table1
输出结果:
3、 手动添加某列值
查找到所有数据后,再在最后一行加入数据(“num总和”,sum(num))
select * from table1
union all/union
select "总和" id, sum(num) from table1
输出结果:
2. with rollup-在分组字段的基础上做汇总统计
这个涉及到with rollup关键词,用在group by之后,用来对分组字段做汇总统计。汇总统计可以用sum()、count()、avg()、min()、max()等函数,或者是一个计算表达式,比如sum()/max()。
下面通过具体的查询语句进行演示,首先我们看一下原始的表数据。

1、平均值
select ifnull(name,'平均'),avg(num) from test group by name with rollup
结果如下:
2、最小值
select coalesce(name,'最小值'),min(num) from test group by name with rollup
结果如下:
3、汇总值/5
select coalesce(name,'汇总值/5'),sum(num)/5 from test group by name with rollup
结果如下: