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

174
Vistas
How can I merge results from a SQL query that returns multiple objects with the same id?

I'm building my first Node.js API. In the endpoint '/posts' I have a return like this:

[
    {
        "POST_ID": 1,
        "POST_TITLE": "Post N.1",
        "POST_DESCRIPTION": "Description for Post N.1",
        "POST_PHOTO_URL": "Url for image 1 of post 1"
    },
    {
        "POST_ID": 1,
        "POST_TITLE": "Post N.1",
        "POST_DESCRIPTION": "Description for Post N.1",
        "POST_PHOTO_URL": "Url for image 2 of post 1"
    },
    {
        "POST_ID": 2,
        "POST_TITLE": "Post N.2",
        "POST_DESCRIPTION": "Description for Post N.2",
        "POST_PHOTO_URL": "Url for image 1 of post 2"
    },
    {
        "POST_ID": 2,
        "POST_TITLE": "Post N.2",
        "POST_DESCRIPTION": "Description for Post N.2",
        "POST_PHOTO_URL": "Url for image 2 of post 2"
    }
]

How can I merge the objects that have the same POST_ID, and make the POST_PHOTO_URL an array that contains all the URLS for the same post?

I want something like this:

responseObj = {
    postId: 0,
    postTitle: "Post N.1",
    postDescription: "Description for Post N.1",
    postImages: ['first_url', 'second_url'],
  };

My SQL Query is: SELECT P.POST_ID, P.POST_TITLE, P.POST_DESCRIPTION, PI.POST_PHOTO_URL FROM POST P INNER JOIN POST_ITEMS AS PI ON P.POST_ID = PI.POST_ID SQL SERVER.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I have no SQL SERVER to test this, but your desired output could probably be created with the following query.

SELECT P.POST_ID AS postId, P.POST_TITLE AS postTitle, P.POST_DESCRIPTION AS postDescription, oa.postImages
FROM POST P
OUTER APPLY(
    SELECT PI.POST_PHOTO_URL AS postImages
    FROM POST_ITEMS PI
    WHERE PI.POST_ID = P.POST_ID
    FOR JSON PATH
) oa

This should return an JSON representation of the desired POST_PHOTO_URLs. You have to parse these to get your array.

result.forEach(r => {
  r.postImages = JSON.parse(r.postImages);
})
about 4 years ago · Juan Pablo Isaza 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