SELECT 表头名 FROM 库名.表名 [WHERE条件] 分组 | 过滤 ;
分组
select列名 count(*)from 表名 group by 列名 条件;
group By注意事项:
1.可以使用单个列,多个列组合,甚至是对列的计算结果
2.分组的依据必须是可以从数据表中获得的数据
3.分组之后是针对子表数据进行操作,不会在显示单行数据等,或者说不能完整的查看单个子表的数据
4. select后面除了聚合函数处理的部分外,最好选取的列都出现在group by子句中
5.NULL 空也会被归类为一种值,所有NULL 的行被分到一张子表中
6.group by出现在where 后,order by 前面
过滤
select 表头名 from 库.表 where 筛选条件 having 筛选条件;
select列名 count(*)from 表名where 条件 group by 列名having 条件;
练习:
1.orderltems表包含每个订单的单独项目,返回每个订单号(order_num)的行数(作为order_lines),并按order_lines对结果排序
mysql> SELECT order_num, COUNT(*) AS order_lines -> FROM orderitems -> GROUP BY order_num -> ORDER BY order_lines; +-----------+-------------+ | order_num | order_lines | +-----------+-------------+ | 20006 | 1 | | 20007 | 1 | | 20008 | 1 | | 20005 | 4 | | 20009 | 4 | +-----------+-------------+ 5 rows in set (0.01 sec)
2.返回一个名为cheapes_item的字段,其中包含每个供应商的最低成本项目(使用Producrs表中的prod-price),并将结果从最低成本到最高成本排序。
mysql> SELECT vend_id, MIN(prod_price) AS cheapest_item -> FROM products -> GROUP BY vend_id -> ORDER BY cheapest_item ASC; +---------+---------------+ | vend_id | cheapest_item | +---------+---------------+ | 1003 | 2.50 | | 1002 | 3.42 | | 1001 | 5.99 | | 1005 | 35.00 | +---------+---------------+ 4 rows in set (0.01 sec)
3.找到最好的客户,为至少100项的每个订单返回订单号(orderlems表中的order num)。
mysql> select order_num from orderitems -> group by order_num -> having sum(quantity) >=100; +-----------+ | order_num | +-----------+ | 20007 | +-----------+ 1 row in set (0.00 sec)
4. 另一种确定最佳客户的方法是根据他们花了多少钱。编写一条SQL语句,返回总价至少为1000的每个订单的订单号(0rderitems表中的order_num)。这里有一个提示:对于这个,你需要计算并求和total(item_price乘以guantiy)。按订单号对结果进行排序。
mysql> select order_num from orderitems -> group by order_num -> having sum(item_price * quantity) >= 1000 -> order by order_num; +-----------+ | order_num | +-----------+ | 20007 | +-----------+ 1 row in set (0.00 sec)