Maximum in group by active record query

二次信任 提交于 2019-12-23 15:44:00

问题


I have a Model which has two attributes (I am showing only two as only those two columns are needed)

MyModel


place_id ------------------------ user_id

1 ---------------------------------- 1

1 ---------------------------------- 2

1 ---------------------------------- 2

3 ---------------------------------- 3

3 ---------------------------------- 2

3 ---------------------------------- 3

3 ---------------------------------- 1

I want to fetch group by maximum records. Basically I want to fetch for a particular place which user has maximum records like for for place_id 1 user 2 has maximum results and for place 3 user 3 has maximum results.


回答1:


If you are specifying a place first you can do:

MyModel.where("place_id=?",place_id).
        group("place_id,user_id").order("count(user_id) DESC").first

If you want to get all the maximums at once, then remove the where clause and iterate through your result set, taking only the first record for each distinct place_id. Or you may be able to add a distinct to the statement above. Something like this?

MyModel.select("DISTINCT(place_id)").
        merge(MyModel.group("place_id,user_id").order("count(user_id) DESC"))

Good luck!



来源:https://stackoverflow.com/questions/6468316/maximum-in-group-by-active-record-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!