Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group By column on SQL Server and concat inner join to that grouped column

So I have this Query that gives me this result: (dont worry about the second ID column)

enter image description here

Is there any way to first Group By "Nombre" but at the same time concat the "Valor" column with the "Nombre" column after it is Grouped?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EXAMPLE:

enter image description here

As this:
(Under column "Nombre"): Lista clasificacion : a, b, c

>Solution :

Without sample data it is hard to tryout, but maybe this can help you

First I create some sample data, but I have no idea if this is correct with your data

declare @Lista table (Id int, Nombre varchar(50))
declare @ListaDetalle table (IdLista int, Valor varchar(10))

insert into @Lista (Id, Nombre) values (1, 'Lista clasfication'), (1, 'Lista clasfication'), (1, 'Lista clasfication'), (7, 'Lista final'), (7, 'Lista final')
insert into @ListaDetalle (IdLista, Valor) values (1, 'a'), (1, 'b'), (1, 'c'), (7, 'Valor 01'), (7, 'Valor 02')

Now we can use this query which returns what you asked in your question

select l.Nombre + ': ' +
       ( select string_agg(ld2.Valor, ',')
         from   @ListaDetalle ld2
         where  ld2.IdLista = l.Id
       ) as Nombre 
from   @Lista l
  inner join @ListaDetalle ld on l.Id = ld.IdLista
group by l.Id, l.Nombre

The result is

Lista clasfication: a,b,c
Lista final: Valor 01,Valor 02
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading