MySQL--分组数据
2024-09-04 23:38:58
1、数据分组
#连接数据库
use newschema;
#查看表中数据
select *from products;
#返回供应商1003提供的产品数目
select count(*) as num_prods from products where vend_id=1003;
2、创建分组
select vend_id,count(*) as num_prods from products group by vend_id;
**Group By 子句必须出现在where自居之后,order by 子句之前。
#使用with rollup
select vend_id,count(*) as num_prods from products group by vend_id with rollup; #使用with rollup关键字,可以得到每个分组以及每个分组汇总级别(针对每个分组)的值。
3、过滤分组
所有类型的where子句都可以用having来替代。唯一差别师where过滤行,而having过滤分组。
select cust_id,count(*) as orders from orders group by cust_id having count(*)>=2;
having和where的差别:where在数据分组前进行过滤,having在数据分组后进行过滤。
select vend_id,count(*) as num_prods
from products
where prod_price>=10
group by vend_id
having count(*)>=2;
分析:where子句过滤所有prod_price至少为10 的行,然后按照cend_id 分组,having子句过滤计数为2或2以上的分组。
select vend_id,count(*) as num_prods
from products
group by vend_id
having count(*)>=2;
4、分组和排序
select order_num,sum(quantity*item_price) as ordertotal
from orderitems
group by order_num
having sum(quantity*item_price)>=50;
select order_num,sum(quantity*item_price) as ordertotal
from orderitems
group by order_num
having sum(quantity*item_price)>=50
order by ordertotal;
5、select子句顺序
下列表是在使用select语句时必须遵循的次序
select |
from |
where |
group by |
having |
order by |
limit |
最新文章
- Android开发 SQLite数据库应用笔记(一)
- cocos2d学习记录
- MongoDB修改器的使用1
- NSString学习
- Pointcut is not well-formed: expecting 'name pattern' at character position
- Mongodb For Windows
- AFNetWorking 的简单使用
- iOS 网络 -- cocoaPods 安装和使用教程
- POJ 2429
- flash player over linux
- win10 如何配置 java jdk1.8环境变量(2017.2.24)
- Php中文件下载功能实现超详细流程分析
- [BZOJ 3745] [COCI 2015] Norma
- promise用法十道题
- Python函数的一点用法
- Java单例模式之懒汉模式线程安全
- Alpha冲刺 - (3/10)
- 北邮新生排位赛2解题报告d-e
- Git 代码管理命令
- DevExpress01:Bar Manager,bar 、Toolbars