SQL聚合查询可算是SQL查询的精华,也是比较难理解的部分,特别是compute、compute by、cube,看上去很相似,但区别还是蛮大的。这里总结的知识点希望能够帮到您。
distinct
distinct主要实现去掉重复数据
举例:
select distinct sex from student; select count(sex), count(distinct sex) from student;
compute和compute by汇总查询
1、对年龄大于的进行汇总
举例:
select age from student where age > 20 order by age compute sum(age) by age;
2、对年龄大于的按照性别进行分组汇总年龄信息
举例:
select id, sex, age from student where age > 20 order by sex, age compute sum(age) by sex;
3、按照年龄分组汇总
举例:
select age from student where age > 20 order by age, id compute sum(age);
4、按照年龄分组,年龄汇总,id找最大值
举例:
select id, age from student where age > 20 order by age compute sum(age), max(id);
compute进行汇总前面是查询的结果,后面一条结果集就是汇总的信息。compute子句中可以添加多个汇总表达式,可以添加的信息如下:
a、 可选by关键字。它是每一列计算指定的行聚合
b、 行聚合函数名称。包括sum、avg、min、max、count等
c、 要对其执行聚合函数的列 compute by适合做先分组后汇总的业务。
compute by后面的列一定要是order by中出现的列。
cube汇总
cube汇总和compute效果类似,但语法较简洁,而且返回的是一个结果集。
举例:
select count(*), sex from student group by sex with cube; select count(*), age, sum(age) from student where age is not null group by age with cube;
cube要结合group by语句完成分组汇总。