分组查询

分组查询
    使用group by 语句对列进行分组
    SELECT column1,column2,column3 ... FROM table group by column having ...
    
    样例表:
create table orders(
    id int,
    product varchar(20),
    price float
);

insert into orders values (1,'电视',900);
insert into orders values (2,'洗衣机',100);
insert into orders values (3,'洗衣粉',90);
insert into orders values (4,'橘子',9);
insert into orders values (5,'洗衣粉',90);

    ~ 对订单表中的商品归类后,显示每一类商品的总价
      分组以后,价格一列一样的分成一组,但只是展示成一行,实际上数据就像叠在一起一样,此时使用聚合函数就是对这些叠在一起的内容进行操作
        select product,sum(price) from orders group by product;
    ~ 查询总价大于100元的商品的名称
        select product,sum(price) from orders group by product having sum(price)>100;
        where语句可以进行过滤,他是分组之前进行过滤,where 语句中是不允许使用聚合函数
        如果想在分组之后进行过滤必须使用having 语句来进行,having语句中可以使用聚合函数
    ~ 查询单价小于100而总价大于100的商品的名称
        分组前先用where语句过滤出单价小于100的
        select product,price from orders where price<100;
        分组以后,因为两条洗衣粉的信息已经叠在一起,这个时候就可以使用聚合函数了
        select product,sum(price) from orders where price<100 group by product having sum(price)>100;
        
使用limit关键字查询部分数据
    SELECT 字段名1,字段名2 ... FROM 表名 LIMIT [OFFSET,]  要查询的记录条数
原文地址:https://www.cnblogs.com/zhuhaofeng/p/15732199.html