Adnan
Adnan

Reputation: 26360

Group by with ActiveRecord in Rails

I have a the following table with rows:

===============================================
id| name  | group1 | group2 | group3 | group4 |
===============================================
1 | Bob   | 1      | 0      | 0      | 1      |
===============================================
2 | Eric  | 0      | 1      | 0      | 1      |
===============================================
3 | Muris | 1      | 0      | 1      | 1      |
===============================================
4 | Angela| 0      | 0      | 0      | 1      |
===============================================

EDIT: The expected result in my view would be as follow, it would output the group name(group1,group2... there is about 30 groups) and in parenthesis the count number of how many users have value 1 for that group.

group1 (2)
group2 (1)
group3 (1)
group4 (4)

All help is appreciated.

Upvotes: 1

Views: 1234

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

I am assuming you want the following results:

group1_sum  2
group2_sum  1
group3_sum  1
group4_sum  4

Following code should return the wanted result:

gt = GroupTally.first(:select => "SUM(group1) AS group1, 
                           SUM(group2) AS group2, 
                           SUM(group3) AS group3, 
                           SUM(group4) AS group4")

p gt.group1 # 2
p gt.group2 # 1
p gt.group3 # 1
p gt.group4 # 4

Upvotes: 2

Related Questions