MySQL分组数据

1. 分组数据 分组计数 select vend_id, count(*) as num_prods from products group by vend_id; rollup关键字 select vend_id, count(*) as num_prods from products group by vend_i...
1. 分组数据
分组计数
select vend_id, count(*) as num_prods from products group by vend_id;

rollup关键字
select vend_id, count(*) as num_prods from products group by vend_id with rollup;

having过滤分组
select cust_id, count(*) as orders from orders group by cust_id having count(*) >= 2;

混合过滤分组
select vend_id, count(*) as num_prods from products where prod_price >= 10 group by vend_id having count(*) >= 2;

select vend_id, count(*) as num_prods from products group by vend_id having count(*) >= 2;

分组和排序
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;

1. group by 对数据进行分组
    建立分组时,指定的所有列都一起计算,不能从个别的列取回数据;
    除聚集计算语句外,select语句中的每个列都必须在group by子句中给出;
    分组列中有null值,则null将作为一个分组返回,如果列中有多行null,将他们分为一组;
2. group by子句必须出现在where子句之后,order by子句之前
3. 使用with rollup关键字,可以得到每个分组以及每个分组汇总级别(针对每个分组)的值
4. having关键字可以过滤分组
    having子句放在group by后面
    having和where语法基本相同
    having在数据分组后进行过滤,where在数据分组前进行过滤
5. group by与order by
    1) group by分组行,但输出可能不是分组的顺序
       order by排序产生的输出
    2) group by只能使用选择列或者表达式列,而且必须使用每个选择列表达式
       order by任意列都可以使用(甚至非选择的列也可以使用)
    3) group by如果与聚集函数一起使用列(或表达式),则必须使用
       order by不一定需要
6. select子句顺序
    子句         说明                   是否必要使用
    select       要返回的列或表达式     是
    from         从中检索数据的表       仅在从表选择数据时使用
    where        行级过滤               否
    group by     分组说明               仅在按组计算聚集时使用
    having       组级过滤               否
    order by     输出排序顺序           否
    limit        要检索的行数           否

原文出处:http://andrew7676.iteye.com/blog/2430838

  • 发表于 2018-09-19 19:22
  • 阅读 ( 334 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除