sql >> Base de Datos >  >> RDS >> Mysql

MySQL:obtenga el enésimo valor más alto para cada grupo en una tabla

Espero que haya una mejor manera, pero puede obtener esto cruzando o no dos subconsultas:

Select mytable.Store, mytable.Dept, mytable.Order, mytable.Amount
from mytable m
inner join 
  (Select Amount from mytable n where m.store = n.store and m.dept = n.dept order by Amount desc limit 2) as high_enough
  on mytable.Amount = high_enough.Amount
left join 
   (Select Amount from mytable n where m.store = n.store and m.dept = n.dept order by Amount desc limit 2) as too_high
  where too_high.Amount is null
group by Store, Dept;