Get top n records for each group with Django queryset
问题 I have a model like the following Table, create table `mytable` ( `person` varchar(10), `groupname` int, `age` int ); And I want to get the 2 oldest people from each group. The original SQL question and answers are here StackOverflow and One of the solutions that work is SELECT person, groupname, age FROM ( SELECT person, groupname, age, @rn := IF(@prev = groupname, @rn + 1, 1) AS rn, @prev := groupname FROM mytable JOIN (SELECT @prev := NULL, @rn := 0) AS vars ORDER BY groupname, age DESC,