提取gmv前50%店铺信息

从表purchase中提取五月和六月,总gmv中,两个月分别贡献前50%的店铺
表purchase字段说明:ID(店铺ID),name(店铺名),dt(日期,格式:‘2019-08-25’),gmv

select a.mon, a.name
from(
	select a.name, date_format(a.dt, '%Y%m') as mon, a.gmv, 
			@gmv_m:=if(date_format(dt, '%Y%m')=@mon, @gmv_m+gmv, gmv) as gmv_m,
			@mon:=date_format(dt, '%Y%m')
	from purchase as a, (select @gmv_m:=0, @mon:='') as b
	order by date_format(dt, '%Y%m'), gmv desc
) as a
join (
	select date_format(dt, '%Y%m') as mon, sum(gmv) as sum
	from purchase
	group by  date_format(dt, '%Y%m')
	) as b
on a.mon=b.mon and a.gmv_m<=b.sum*0.5

如有错误,欢迎指正!

你可能感兴趣的:(数据分析笔试SQL)