jalagrange
jalagrange

Reputation: 2381

How to group and count in rails

I am currently trying to create graph statistics for jobs in a PBS. I have a jobs model that has many fields, among them is a "Group" field. I would like to know how many jobs each group has executed. For that, I need the following query:

SELECT 
jobs.`group`,
COUNT(`group`) AS 'number_of_jobs'
FROM jobs
GROUP BY jobs.`group`

Which returns 2 columns, the group name and how many jobs that group has executed, whoever, I am unable to do so in Ruby on rails. Any help would be appreciated.

Upvotes: 1

Views: 658

Answers (2)

MKumar
MKumar

Reputation: 1524

Assuming that you have model named Job for jobs tables

Job.find(
          :all,
          :select => 'group, COUNT(group) AS number_of_jobs',
          :group  => 'group'
      )

Upvotes: 1

Salil
Salil

Reputation: 47482

group is keyword for mysql so use (`) backtics for it

Job.find(
          :all,
          :select => '`group`, COUNT(`group`) AS number_of_jobs',
          :group  => '`group`'
      )

No check though

Upvotes: 3

Related Questions