In case of amount
matching for different agentid
s, then, I believe, ranks should be assigned same.
This solution should help you:
select
/*case when rank>6 then '' else rank end as */
rank, agentid, amount
from (
select agentid, @ca:=amount amount
, case when @pa=@ca then @rn:=@rn
else @rn:=( @rn + 1 )
end as rank
, @pa:=@ca as temp_currAmount
from ( select agentid, sum(amount) as amount
from agents
group by agentid
order by amount
) amounts_summary,
(select @pa:=0, @c0:=0,
@rn:=0) row_nums
order by rank desc
) results
where rank > 6
order by rank
;
Demo @ MySQL 5.6.6 Fiddle
And if you want no display ranks greater than '6'
but empty, then
just uncomment the case
line and comment the where
condition line
select
case when rank>6 then '' else rank end as
rank, agentid, amount
from (
select agentid, @ca:=amount amount
, case when @pa=@ca then @rn:=@rn
else @rn:=( @rn + 1 )
end as rank
, @pa:=@ca as temp_currAmount
from ( select agentid, sum(amount) as amount
from agents
group by agentid
order by amount
) amounts_summary,
(select @pa:=0, @ca:=0,
@rn:=0) row_nums
order by rank
) results
-- where rank > 6
order by rank
;
You can modify asc
or desc
as required.
Demo @ MySQL 5.6.6 Fiddle