Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

826
Views
ActiveRecord Query. Group by multiple columns from multiple tables
Attendance.joins(:user).group(:email, :name).count

The query above gives me the below results. "User 1" had 2 attendances and "User 2" had 6 attendance, plus I have access to the user name and email.

{["email@example.com", "User 1"]=>2, ["email2@example.com", "User 2"]=>6]}

This is great except I'd really like the User.id to be included as well. I can't group by the ID because then each record will be unique instead of being grouped by email and name. The below is what i'd like:

{[1, "email@example.com", "User 1"]=>2, [2, "email2@example.com", "User 2"]=>6]}

Any help would be appreciated.

Answer Attendance.joins(:user).group(:email, :name, 'attendances.user_id').count

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Attendance.joins(:user).group(:email, :name, 'attendances.user_id').count
over 4 years ago · Santiago Trujillo Report

0

# collect required fields and group by email, name
grouped_attendance = Attendance.joins(:user).pluck(:id, :email, :name).group_by{|r| [r[1], r[2]]}

# calculate the counts
attendance_counts = grouped_attendance.each{|k,v| grouped_attendance[k] = v.count}

Depending on your setup, but above should be fast enough as you are not instantiating ActiveRecord objects.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!