【MySQL group by 常见聚合函数】

 目录

分组 Group By

分组计数 Group By + Count

分组去重计数 Group By + Distinct Count

分组条件求和  Group By + Distinct Count + if(case when)

分组求和 Group By + Sum

分组条件求和  Group By + Sum + if(case when)

分组筛选

常用5个聚合函数


常见聚合函数count、sum、min、max、avg的使用

CommodityPrice表

namecategoryamountweightunitprice
大米粮油15000g30
花生油粮油15L135
面条粮油1900g12
洗洁精厨卫11L16
小蛋糕熟食1200g10
上海青蔬菜1250g5.5
猪肉肉类1300g16
猪肉肉类2800g35
牛肉肉类1300g40
牛肉肉类1500g60
羊肉肉类2300g55

分组 Group By

-- 分组查询category值
select category from CommodityPrice group by category  

分组计数 Group By + Count

-- 分组计算每个category的对应记录数
select category, count(1) from CommodityPrice group by category

分组去重计数 Group By + Distinct Count

-- 分组计数每个category下name的非重复数量
select category, count(distinct name) from CommodityPrice 
group by category

分组条件求和  Group By + Distinct Count + if(case when)

-- 分组计数每个category下amount<2的name数量
select category, 
count(distinct name, if(amount<2, true, null)),
count(distinct name, case when amount>1 then null else name end) 
from CommodityPrice group by category

分组求和 Group By + Sum

-- 分组计数每个category下amount总和
select category, sum(amount) from CommodityPrice group by category

分组条件求和  Group By + Sum + if(case when)

-- 分组计数每个category下amount<=1的price总和
select category, 
sum(case when amount>1 then 0 else price end), 
sum(if(amount<=1, price, 0)) 
from CommodityPrice group by category

分组筛选

  • 满足HAVING 条件的结果将被显示
  • HAVING 不能单独使用,必须要跟 group by 一起使用
-- 分组计数每个category下amount<=1的price总和,并筛选出total_price>1的值
select category, sum(if(amount<=1, price, 0)) total_price
from CommodityPrice group by category
having total_price>1

常用5个聚合函数

-- 如下语句中的case when都可以用if(amount<=1, price, null)替代
select category, 
sum(case when amount>1 then 0 else price end) total_price, 
count(distinct price, case when amount>1 then null else price end), 
max(case when amount>1 then null else price end), 
min(case when amount>1 then null else price end), 
avg(case when amount>1 then null else price end)
from CommodityPrice 
group by category 
having total_price>1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wo.austin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值