Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
String_agg for multiple columns

I have the following select

$repairs = DB::select(DB::raw('
            select r.id repair_id, w.name, w.surname
                from repairs r
                    join repair_worker rw on r.id = rw.repair_id
                    join workers w on w.id = rw.worker_id
                where r.vehicle_id = ?
                group by w.name, w.surname, r.id
           '),[$vehicle->id]);

and I am trying to get w.name and w.surname into one field, separated by a comma for example. There is a function string_agg(column, ',') but I am having no luck to get it working. I always get syntax error.

My try:

$repairs = DB::select(DB::raw('
                select r.id repair_id, string_agg(w.name, w.surname, ', ') workers
                    from repairs r
                        join repair_worker rw on r.id = rw.repair_id
                        join workers w on w.id = rw.worker_id
                    where r.vehicle_id = ?
                    group by r.id
          '),[$vehicle->id]);

How would you do it?

I am using the newest Postgresql 9+

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Use the || operator to perform string concatenation, then aggregate this result.

$repairs = DB::select(DB::raw("
    select r.id repair_id, string_agg(w.name || ' ' || w.surname, ', ') workers
    from repairs r
        join repair_worker rw on r.id = rw.repair_id
        join workers w on w.id = rw.worker_id
    where r.vehicle_id = ?
    group by r.id
    "),[$vehicle->id]);
over 4 years ago · Santiago Trujillo Denunciar

0

try this?

$repairs = DB::select(DB::raw("
                select r.id repair_id, string_agg(concat(w.name, ',',w.surname), ', ') workers
                    from repairs r
                        join repair_worker rw on r.id = rw.repair_id
                        join workers w on w.id = rw.worker_id
                    where r.vehicle_id = ?
                    group by r.id
          "),[$vehicle->id]);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda