sql函数大全及举例_SQL查询技巧汇总-聚合查询

SQL聚合查询可算是SQL查询的精华,也是比较难理解的部分,特别是compute、compute by、cube,看上去很相似,但区别还是蛮大的。这里总结的知识点希望能够帮到您。

008a1979e5245beda57d23945ed6a65f.png

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);

07e38e919c5353526d3181ad6aad726f.png

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中出现的列。

4090497d6d96c5c4a56b141ae757b652.png

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语句完成分组汇总。

40ba16d7f36bba8de852990864c4d6f8.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值