能不能把表结构和样例数据给一部分出来啊?我的思路是用子查询,先通过子查询,按发货方式汇总发货量,找到排名前五的,然后外面关联原表,再按发货方式和国家汇总发货量,就取到了排名前五的国家;伪代码如下: select 发货方式 ,国家 ,sum(发货量) from table1 a inner join (select 发货方式 ,sum(发货量) from table1 a where 时间 between 4月 and 5月 group by 发货方式 order by sum(发货量) desc limit 5) b on a.发货方式 = b.发货方式 where a.发货方式 = b.发货方式 and where 时间 between 4月 and 5月 group by 发货方式 ,国家 order by sum(发货量) desc 不对,这种取法可以取到每种发货方式国家发货的发货量排列顺序,可是没办法取到排名前5的国家
想了想,想了个最笨的方法,想不出更好的方法了,其他人如果有更好的方法,还望不吝赐教: select 发货方式 ,国家 ,发货量_sum ,if( @objno = a.国家, @rank:= @rank+1, @rank:=1) as row_number ,@objno = a.国家 from (select 发货方式 ,国家 ,sum(发货量) as 发货量_sum from table1 a inner join (select 发货方式 ,sum(发货量) from table1 a where 时间 between 4月 and 5月 group by 发货方式 order by sum(发货量) desc limit 5) b on a.发货方式 = b.发货方式 where a.发货方式 = b.发货方式 and where 时间 between 4月 and 5月 group by 发货方式 ,国家 order by 发货方式 ,国家,sum(发货量) desc )a ,(@objno:=NULL, @rank:=0) b where row_number<=5 因为mysql本身不支持诸如oracl等支持的over(partition by )函数,所以写起来有点儿费劲
select
发货方式
,国家
,sum(发货量)
from table1 a
inner join (select
发货方式
,sum(发货量)
from table1 a
where 时间 between 4月 and 5月
group by 发货方式
order by sum(发货量) desc
limit 5) b
on a.发货方式 = b.发货方式
where a.发货方式 = b.发货方式
and where 时间 between 4月 and 5月
group by 发货方式 ,国家
order by sum(发货量) desc
不对,这种取法可以取到每种发货方式国家发货的发货量排列顺序,可是没办法取到排名前5的国家
select
发货方式
,国家
,发货量_sum
,if( @objno = a.国家,
@rank:= @rank+1,
@rank:=1) as row_number
,@objno = a.国家
from
(select
发货方式
,国家
,sum(发货量) as 发货量_sum
from table1 a
inner join (select
发货方式
,sum(发货量)
from table1 a
where 时间 between 4月 and 5月
group by 发货方式
order by sum(发货量) desc
limit 5) b
on a.发货方式 = b.发货方式
where a.发货方式 = b.发货方式
and where 时间 between 4月 and 5月
group by 发货方式 ,国家
order by 发货方式
,国家,sum(发货量) desc
)a
,(@objno:=NULL, @rank:=0) b
where row_number<=5
因为mysql本身不支持诸如oracl等支持的over(partition by )函数,所以写起来有点儿费劲