/*------------------------------------*/ /* Another way to RANK rows in MySQL */ /*------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Create a rank variable /* Subquery with an order by /* Add the rank in outer query /*----------------------------------------------------------------------------*/ SET @rank_lo2hi:=0; SELECT @rank_lo2hi:=@rank_lo2hi+1 as "rank low to high", vendor, amount FROM (SELECT vendor, amount from payment group by amount order by amount) AS r ORDER BY "rank low to high"; /*----------------------------------------------------------------------------*/ SET @rank_hi2lo:=0; SELECT @rank_hi2lo:=@rank_hi2lo+1 as "rank high to low", vendor, tot_amt FROM (SELECT vendor, sum(amount) tot_amt from payment group by vendor order by tot_amt desc) AS r2 ORDER BY 1 desc;