Mysql
 sql >> Datenbank >  >> RDS >> Mysql

MySQL:Hole den n-thöchsten Wert für jede Gruppe in einer Tabelle

Ich hoffe, es gibt einen besseren Weg, aber Sie können dies erreichen, indem Sie zwei Unterabfragen schneiden oder nicht:

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;