Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

827
Visualizações
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 Respostas
Responde à pergunta

0

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda