1. 程式人生 > >Mysql分組後以最大值為條件獲取其他欄位

Mysql分組後以最大值為條件獲取其他欄位

需求:按照渠道,城市,省份分組獲取最高訂單日,最高日訂單數

思路:先獲取分組後每組的訂單排序,再給他們的排序附上號數,再連結串列獲取1號的資料欄位

SELECT o.fromType,o.provinceId,o.provinceName,o.cityId,o.cityName,SUM(o.orderNum) As orderNum ,SUM(o.orderSum) As orderSum 
,SUM(o.accountNum) As accountNum,SUM(o.accountSum) As accountSum,SUM(o.cancelNum) As cancelNum,SUM(o.cancelSum) As cancelSum 
from order o group by o.fromType,o.provinceId,o.cityId;

先獲取其它需求需要的欄位,

結果:

select sum(o.orderNum) as sumOrderNum,o.fromType,o.provinceId,o.cityId,o.statDate from  order o where o.statDate between '2018-09-01' and '2018-10-20' group  by o.statDate,o.fromType,o.provinceId,o.cityId order by o.fromType,o.provinceId,o.cityId,sumOrderNum desc;

獲取按照城市,渠道,省份,日期分組後,按照總訂單數倒序按分好組的順序進行排序,代表著這一天這個城市這個省份城市渠道一共下了多少單,分在一起以總訂單數倒序,order by後面跟的就是以什麼欄位的形式排序在一起,desc是根據哪個欄位降序

結果:

select @rownum:=case when @fromType=fromType and @provinceId = provinceId and @cityId= cityId then @rownum+1 else 1  end as count_of_total,
@fromType:=t.fromType AS fromType,@provinceId:= t.provinceId AS provinceId,@cityId:= t.cityId AS 
cityId,t.sumOrderNum as maxOrderNum,t.statDate as maxOrderDate from(select sum(o.orderNum) as sumOrderNum,o.fromType,o.provinceId,o.cityId,o.statDate from  
order o where o.statDate between '2018-09-01' and '2018-10-20' group  by o.statDate,o.fromType,o.provinceId,o.cityId order by o.fromType,o.provinceId,o.cityId,sum(o.orderNum)desc)t;

再給這些資料一個排名,按組的形式。

定義一個rownum變數一開始為空所以為1,固然一開始排好序,所以第一個肯定最大,然後獲取後面的資料欄位,一樣就加1,排序下去,不一樣就重新賦1,獲取到排名,provinceId之類的值根據上個表獲取

結果:

SELECT o.fromType,o.provinceId,o.provinceName,o.cityId,o.cityName,SUM(o.orderNum) As orderNum ,SUM(o.orderSum) As orderSum 
,SUM(o.accountNum) As accountNum,SUM(o.accountSum) As accountSum,SUM(o.cancelNum) As cancelNum,SUM(o.cancelSum) As cancelSum ,maxOrderNum,maxOrderDate
from order o 
left join(
select @rownum:=case when @fromType=fromType and @provinceId = provinceId and @cityId= cityId then @rownum+1 else 1  end as count_of_total,
@fromType:=t.fromType AS fromType,@provinceId:= t.provinceId AS provinceId,@cityId:= t.cityId AS 
cityId,t.sumOrderNum as maxOrderNum,t.statDate as maxOrderDate from(select sum(o.orderNum) as sumOrderNum,o.fromType,o.provinceId,o.cityId,o.statDate from  
order o where o.statDate between '2018-09-01' and '2018-10-20' group  by o.statDate,o.fromType,o.provinceId,o.cityId order by o.fromType,o.provinceId,o.cityId,sum(o.orderNum)desc)t
)a
on a.fromType = o.fromType and a.provinceId = o.provinceId and a.cityId = o.cityId and a.count_of_total =1 where o.statDate between '2018-09-01' and '2018-10-20'
group by o.fromType,o.provinceId,o.cityId;

再和原來的欄位來個連結串列查詢合在一起

結果: