Does RAILS have GROUP BY…WITH ROLLUP query?

[亡魂溺海] 提交于 2020-01-05 11:03:40

问题


GROUP BY... WITH ROLLUP is a cool feature in sql.

Does Rails support ROLLUP ?

How can I write the query like,

.group('column1, column2,....')

回答1:


I normally use it like

@rollup = People.select(:occupation, :state, 'COUNT(`state`) as cnt')
             .group(:occupation, 'state WITH ROLLUP')
             .to_a.map(&:attributes)

then in my view use @rollup.first["state"] etc.




回答2:


You can use the RollUp clause in the group method of ruby. Let take an example, we have sql query like

SELECT *
FROM Lead
GROUP BY ROLLUP(LeadSource)

In rails we can map this query like:

Lead.group("lead_source with rollup")


来源:https://stackoverflow.com/questions/33007596/does-rails-have-group-by-with-rollup-query

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