1
You need to use the STRING_AGG aggregation function:
SELECT
pga.Titulo,
STRING_AGG(e.Codigo,', ') as Codigos
FROM Qualidade_Diagrama_Processo_Grupo_Acao pga
JOIN Qualidade_Diagrama_Acao_Entidade ae on (ae.Id_Proc_Grupo_Acao = pga.Id)
JOIN Qualidade_Diagrama_Entidade e on (e.Id = ae.Id_Entidade)
WHERE ae.Id_Proc_Grupo_Acao = 48
Group by pga.Titulo
Edit:
After the database information is SQL Server 2012, and it does not have the String_agg function:
You can use a CTE (common table Expressions) recursively:
Considering the following table:
create table tabela
(
id integer,
titulo varchar(10));
insert into tabela values (1, 'TESTE');
insert into tabela values (2, 'TESTE');
insert into tabela values (3, 'TESTE');
insert into tabela values (4, 'TESTE');
insert into tabela values (5, 'TESTE');
insert into tabela values (6, 'TESTE');
insert into tabela values (7, 'TESTE');
The query would be:
WITH CTE (Id, ids, titulos, LENGTH) AS
(SELECT 0,
CAST('' AS VARCHAR(8000)),
CAST(t.titulo AS VARCHAR(8000)),
0
FROM tabela t
GROUP BY t.titulo
UNION ALL SELECT p.Id,
CAST(ids + CASE
WHEN LENGTH = 0 THEN ''
ELSE ', '
END + CAST(p.id AS VARCHAR(8000)) AS VARCHAR(8000)),
CAST(titulo AS VARCHAR(8000)),
LENGTH + 1
FROM CTE c
INNER JOIN tabela p ON c.titulos = p.titulo
WHERE p.id > c.id )
SELECT ids,
titulos
FROM
(SELECT Id,
ids,
RANK() OVER (PARTITION BY titulos
ORDER BY LENGTH DESC), titulos
FROM CTE) D (Id, ids, rank, titulos)
WHERE rank = 1 ;
Upshot:
ids titulos
1, 2, 3, 4, 5, 6, 7 TESTE
I put in the Sqlfiddle
Do you have any questions about pivot table here you can help, this is one: https://answall.com/questions/307567/placements-of-a-line-in-columns
– Ricardo Pontual