0

I need to display the top4 and lease 4 rows based Amount and group by agentId but here rank is showing wrong And how to show least(last 4 rows?) schema:

 AgentID amount 
    1      3000
    1      3200
    2      9000
 SELECT Agentid,SUM(AmountRecevied) as Amount,@rownum := @rownum + 1 AS Rank
 FROM collection ,(SELECT @rownum := 0) r
 GROUP BY AgentID
 ORDER BY Amount DESC
 limit 4;

enter image description here

user123
  • 820
  • 3
  • 14
  • 34

3 Answers3

2

Try this way:

SELECT T.Agentid,T.Amount, @rownum := @rownum - 1 AS Rank
 FROM
 (SELECT Agentid,SUM(AmountRecevied) as Amount
 FROM collection 
 GROUP BY AgentID
 ORDER BY Amount
 LIMIT 4) T,(SELECT @rownum := 11) r
Raging Bull
  • 18,593
  • 13
  • 50
  • 55
1

Try this :

SELECT
   C.*,
   @rownum := @rownum + 1 AS Rank
FROM (
   SELECT
     Agentid,
     SUM(AmountRecevied) as Amount
   FROM collection
   GROUP BY AgentID
   ORDER BY Amount DESC
   LIMIT 4
) AS C, (SELECT @rownum := 0) r
Tanatos
  • 1,857
  • 1
  • 13
  • 12
1

In case of amount matching for different agentids, 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

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82