Remis07
Remis07

Reputation: 377

Get sum of a group by count

So please imagine i have this sql table : User :

id | name | city

1 | name1 | city1

2 | name2 | city2

3 | name3 | city1

4 | name4 | city3

So until now by doing this in my controller:

@cities = User.group(:city).count 

and by doing something like this in my view:

<%= "#{city} (#{count})" %> 

I got this :

city1 (2)

city2 (1)

city3 (1)

What i need now is to add a line which sum the count of each city like this :

All (4)

I don't want to make a new sql query for this, because i'm pretty sure there is a cleaner way to do it.

I Hope that i was clear, thanks !

Upvotes: 0

Views: 5639

Answers (1)

bluehallu
bluehallu

Reputation: 10285

You won't be able to do this in a single SQL query unless you craft some fancy SQL yourself. If performance is not a problem, I would aggregate this on the controller:

counts = User.group(:city).count
total = counts.values.sum

Upvotes: 6

Related Questions