mysql分组后占比、累计占比和排序计算方法

1.求group by之后和的占比
先做group by分组汇总,再单独inner join连接到和,最后分组结果除以连接到的和

select 
	ifnull(hour_diff,'--合计--') hour_diff,count(1) cnt,count(1)/tot pct
from 
	(select timestampdiff(hour,createtime,activate_time) hour_diff from t_consumer) w
inner join 
	(select count(1) tot from t_consumer) c 
group by 
	hour_diff 
with rollup;	

2.求group by之后和的累计占比
先求group by之后和的占比,再利用@s参数对占比进行累加

set @s=0;
select *,@s:=@s+pct cul_pct
from
	(select 
		ifnull(hour_diff,'--合计--') hour_diff,count(1) cnt,count(1)/tot pct
	from 
		(select timestampdiff(hour,createtime,activate_time) hour_diff from t_consumer) w
	inner join 
		(select count(1) tot from t_consumer) c 
	group by hour_diff
	with rollup
	) wc;

3.对每行数据进行排序
对每行数据利用@rank参数从1开始累加即可排序

set @s=0;
set @rank=0;
select *,@s:=@s+pct cul_pct,@rank:=@rank+1 rank
from
	(select 
		ifnull(hour_diff,'--合计--') hour_diff,count(1) cnt,count(1)/tot pct
	from 
		(select timestampdiff(hour,createtime,activate_time) hour_diff from t_consumer) w
	inner join 
		(select count(1) tot from t_consumer) c 
	group by 
		hour_diff
	with rollup) wc;
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值