Get top N items per group in Ruby on Rails -
i have model fields "date" , "frequency" (frequency integer). i'm trying top 5 frequencies per date. want group date, top 5 per group.
what have far retrieves top 1 in group:
observation.channel("channelone").order('date', 'frequency desc').group(:date).having('frequency = max(frequency)')
i want max(frequency) plus second, third, fourth , fifth largest per date.
sorry if simple or if terminology off; i've started rails :)
you can use this:
observation .select("obs1.*") .from("observations obs1") .joins("left join observations obs2 on obs1.date = obs2.date , obs1.frequency <= obs2.frequency") .group("obs1.date, obs1.id") .having("count(*) <= 5") .order("obs1.date, obs2.frequency")
this query returns top 5 frequencies each date.
Comments
Post a Comment