当我使用User.count(:all, :group => "name")
时,我会得到多行,但这不是我想要的。我想要的是行数。我怎么能得到它?
答案 0 :(得分:30)
目前(18.03.2014
- Rails 4.0.3
)这是正确的语法:
Model.group("field_name").count
它返回带有计数值的哈希值 e.g。
SurveyReport.find(30).reports.group("status").count
#=> {
"pdf_generated" => 56
}
答案 1 :(得分:25)
User.count
将为您提供总用户数并转换为以下SQL:SELECT count(*) AS count_all FROM "users"
User.count(:all, :group => 'name')
会为您提供唯一名称列表及其计数,并转换为此SQL:SELECT count(*) AS count_all, name AS name FROM "users" GROUP BY name
我怀疑你想要上面的选项1,但我不清楚你想要/需要什么。
答案 2 :(得分:12)
您可能想要计算用户的不同名称吗?
User.count(:name, :distinct => true)
如果您的数据库中有名为John,John,Jane,Joey(例如)的用户,将返回3。
________
| name |
|--------|
| John |
| John |
| Jane |
| Joey |
|________|
答案 3 :(得分:5)
尝试使用User.find(:all,:group =>“name”)。count
祝你好运!答案 4 :(得分:0)
我发现了一种似乎可行的奇怪方法。要对分组计数返回的行进行计数。
________
| name |
|--------|
| Bob |
| Bob |
| Joe |
| Susan |
|________|
User.group(:name).count
# SELECT COUNT(*) AS count_all
# FROM "users"
# GROUP BY "users"."name"
=> {
"Bob" => 2,
"Joe" => 1,
"Susan" => 1
}
User.group(:name).count.count
=> 5
我遇到了一些有趣的事情,但是它很hacky,因为它将增加每一行的计数,并且在活跃的记录领域中表现不佳。我不记得是否能够将其添加到Arel / ActiveRecord查询中。
SELECT COUNT(*) OVER() AS count, COUNT(*) AS count_all
FROM "users"
GROUP BY "users"."name"
[
{ count: 3, count_all: 2, name: "Bob" },
{ count: 3, count_all: 1, name: "Joe" },
{ count: 3, count_all: 1, name: "Susan" }
]