我有一个用于统计目的的查询。它分解了登录给定次数的用户数量。用户 has_many 安装和安装有一个 login_count。
select total_login as 'logins', count(*) as `users`
from (select u.user_id, sum(login_count) as total_login
from user u
inner join installation i on u.user_id = i.user_id
group by u.user_id) g
group by total_login;
+--------+-------+
| logins | users |
+--------+-------+
| 2 | 3 |
| 6 | 7 |
| 10 | 2 |
| 19 | 1 |
+--------+-------+
是否有一些优雅的 ActiveRecord 风格
find
获取相同的信息?理想情况下作为登录名和用户的散列集合:{ 2=>3, 6=>7, ...
我知道我可以直接使用 sql 但想知道如何在 rails 3 中解决这个问题。
最佳答案
# Our relation variables(RelVars)
U =Table(:user, :as => 'U')
I =Table(:installation, :as => 'I')
# perform operations on relations
G =U.join(I) #(implicit) will reference final joined relationship
#(explicit) predicate = Arel::Predicates::Equality.new U[:user_id], I[:user_id]
G =U.join(I).on( U[:user_id].eq(I[:user_id] )
# Keep in mind you MUST PROJECT for this to make sense
G.project(U[:user_id], I[:login_count].sum.as('total_login'))
# Now you can group
G=G.group(U[:user_id])
#from this group you can project and group again (or group and project)
# for the final relation
TL=G.project(G[:total_login].as('logins') G[:id].count.as('users')).group(G[:total_login])
请记住,这非常冗长,因为我想向您展示操作顺序,而不仅仅是“这是代码”。代码实际上可以用一半的代码编写。
毛茸茸的部分是Count()
通常,SELECT 中未在聚合中使用的任何属性都应出现在 GROUP BY 中,因此要小心 count()
为什么要按 total_login 计数分组?
在一天结束时,我只会问你为什么不计算所有安装的总登录次数,因为用户信息与最外层计数分组无关。
关于ruby-on-rails - 使用 Rails 查询语言进行复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2909002/