一、group by
对完整的数据表进行划分子表,划分的依是,指定数据列中值一样的会被划分到同一个子表中,然后使用聚合函数对子表中的数据进行计算比如获取每一生产商定价最高的产品等~
注意事项
1.可以使用单个列,多个列组合,甚至是对列的计算结果
2.分组的依据必须是可以从数据表中获得的数据
3.分组之后是针对子表数据进行操作,不会在显示单行数据等,或者说不能完整的查看单个子表的数据
4.select后面除了聚合函数处理的部分外,最好选取的列都出现在group by子句中
5.NULL 空也会被归类为一种值,所有NULL的行被分到一张子表中
6.group by 出现在where 后,order by 前面
不支持后面加聚合函数,可以再前面加,不适用并列后分组,
格式:select 列名 count(*)from 表名 group by 列名 条件;
二、条件筛选
格式:select 列名 count(*)from 表名where 条件 group by 列名having 条件 order by 列名;
三、实验
orderltems表包含每个订单的单独项目。编写一条SQL语句,返回每个订单号(order_num)的行数(作为order_lines),并按order_lines对结果排序。
编写一条SQL语句,返回一个名为cheapes_item的字段,其中包含每个供应商的最低成本项目(使用Producrs表中的prod-price),并将结果从最低成本到最高成本排序。
找到最好的客户很重要。编写一条SOL语句,为至少100项的每个订单返回订单号(orderlems表中的order num)。
另一种确定最佳客户的方法是根据他们花了多少钱。编写一条SQL语句,返回总价至少为1000的每个订单的订单号(0rderitems表中的order_num)。这里有一个提示:对于这个,你需要计算并求和total(item_price乘以guantiy)。按订单号对结果进行排序。
四、嵌套
格式:select 展示列 from 表名 where 列名A in ( 查询列名A的信息 );
条件嵌套
三层嵌套
将查询作为结果展示
格式:select 列名,(展示的数据 from 表1 where 表2.相同列=表2.相同列)as 别名 from 表1;
五、嵌套实验
1.使用子查询 ,返回购买了价格为 10 或以上的商品的客户列表。您需要使用0rdkrltems表来查找匹配的订单号(order_num),然后使用Orders表来检索每个匹配订单的客户 ID(cust_id) 。
select distinct cust_id from orders where order_num in ( select order_num from orderitems where item_price >= 10) ;
select order_date from orders where order_num in(select order_num from orderitems where prod_id = 'ANV01');
select cust_email from customers where cust_id in(
select cust_id from orders
where order_num in(select order_num from orderitems where prod_id = 'ANV01'));
select prod_name,(select sum(quantity) from orderitems where
orderitems.prod_id=products .prod_id ) as quant_sold from products ;