How to count group by rows in rails?

Viewed 29844

When I use User.count(:all, :group => "name"), I get multiple rows, but it's not what I want. What I want is the count of the rows. How can I get it?

5 Answers

I found an odd way that seems to work. To count the rows returned from the grouping counts.

User Table Example

________
| name   |
|--------|
| Bob    |
| Bob    |
| Joe    |
| Susan  |
|________|

Counts in the Groups


User.group(:name).count

# SELECT COUNT(*) AS count_all
# FROM "users"
# GROUP BY "users"."name"

=> {
  "Bob" => 2,
  "Joe" => 1,
  "Susan" => 1
}

Row Count from the Counts in the Groups

User.group(:name).count.count

=> 5

Something Hacky

Here's something interesting I ran into, but it's quite hacky as it will add the count to every row, and doesn't play too well in active record land. I don't remember if I was able to get this into an Arel / ActiveRecord query.

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" }
]
Related