vietstone
vietstone

Reputation: 9092

Rails count sum avg for multiple columns, not group by

I'm new to Rails.

I know that 'group' on multiple columns is OK. But I don't want that, I want count (or sum, or avg) on multiple columns.

I know:

issues = Issue.group(:tracker_id).count(:subject)

have the query:

SELECT COUNT(`issues`.`subject`) AS count_subject, tracker_id AS tracker_id FROM `issues` GROUP BY tracker_id

But it only count one column 'subject'. I tried to add one more column (status_id) as 2 statements below, but they don't work:

1. issues = Issue.group(:tracker_id).count(:subject).count(:status_id)

2. issues = Issue.group(:tracker_id).count(:subject, :status_id)

How can I do that? Thank you.

Upvotes: 0

Views: 1934

Answers (1)

vietstone
vietstone

Reputation: 9092

Thanks to: group by + sum on multiple columns in rails 3

I can do with some SQL:

issues = Issue.group(:tracker_id)
        .select([:tracker_id, "COUNT(subject)", "COUNT(status_id)"])

Don't know is this the best?

Upvotes: 0

Related Questions