set @a=0; set @rn = 1; SELECT t.a,t.b,t.c,t.rn from( SELECT t.*,case WHEN @a = a THEN @rn := @rn + 1 ELSE @rn := 1 END as rn ,@a := t.a aa from( SELECT 1 a,2 b,1 c UNION SELECT 1 a, 3 b,2 c union SELECT 1 a, 6 b,3 c union SELECT 1 a, 5 b,4 c union SELECT 2 a,2 b,5 c UNION SELECT 2 a, 3 b,6 c union SELECT 2 a, 6 b,7 c union SELECT 2 a, 5 b,8 c ) t ORDER BY t.a,t.b DESC ) t where t.rn > 1