博客
关于我
SQL必知必会 第10课 分组数据
阅读量:179 次
发布时间:2019-02-28

本文共 918 字,大约阅读时间需要 3 分钟。

10.1 数据分组

分组可以将数据分为多个逻辑组,对每个组进行聚集计算。

10.2 创建分组

# GROUP BY 子句指示DBMS按照vend_id 排序并分组数据select vend_id, count(*) as num_prodsfrom productsgroup by vend_id;

在这里插入图片描述

10.3 过滤分组

通过HAVING子句

# 过滤出两个以上订单的分组select cust_id, count(*) as orders from orders group by cust_idhaving count(*) >= 2;

在这里插入图片描述

WHERE 在数据分组前进行过滤,而HAVING 在数据分组之后进行过滤。

# 列出具有两个以上产品且其价格大于等于4的供应商select vend_id, count(*) as onum_prods from productswhere prod_price >= 4group by vend_idhaving count(*) >= 2

在这里插入图片描述

10.4 分组和排序

group by 和 order by 的区别

ORDER BY GROUP BY
对产生的输出排序 对行分组,但输出可能不是分组的顺序
任意列都可以使用 只可能使用选择列或表达式列,而且必须使用每个选择列表达式
不一定需要 如果与聚集函数一起使用列(或表达式),则必须使用

一般在使用GROUP BY子句时,应该也给出ORDER BY子句。这是保证数据正确排序的唯一方法。

# 按订购物品的数目排序输出select order_num, count(*) as items from orderItemsgroup by order_numhaving count(*) >= 3order by items, order_num;

在这里插入图片描述

10.5 select 子句顺序

子句 说明 是否必须使用
SELECT 要返回的列或表达式
FROM 从中检索数据的表 仅在从表选择数据时使用
WHERE 行级过滤
GROUP BY 分组说明 仅在按组计算聚集时使用
HAVING 组级过滤
ORDER BY 输出排序顺序

转载地址:http://jgpn.baihongyu.com/

你可能感兴趣的文章
Nginx实战经验分享:从小白到专家的成长历程!
查看>>
Nginx实现反向代理负载均衡
查看>>
nginx实现负载均衡
查看>>
nginx开机启动脚本
查看>>
nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
查看>>
nginx总结及使用Docker创建nginx教程
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>
nginx最最最详细教程来了
查看>>
Nginx服务器---正向代理
查看>>
Nginx服务器上安装SSL证书
查看>>
Nginx服务器的安装
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>
nginx添加模块与https支持
查看>>
Nginx用户认证
查看>>
Nginx的location匹配规则的关键问题详解
查看>>
Nginx的Rewrite正则表达式,匹配非某单词
查看>>