0

I have a simple query that returns 2 rows as it is joining 2 tables. The query is this:

SELECT 
    id, fecha, tipo, fuente, origen, estado, gravedad, cliente, 
    sectores, datos, idInforme, idDepartamento
FROM 
    Informe I
INNER JOIN 
    InformeDepartamento ID ON I.ID = ID.idInforme

enter image description here

What I need is only to return a single row with the 'idDepartamento' column merged and separated by commas. So the content is 1,4

How can I accomplish this? I've tried with PIVOT but it did not work as I think it is not the right approach for this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
NicoRiff
  • 4,803
  • 3
  • 25
  • 54

2 Answers2

1

You can use STUFF and XML path to get what you need. Here is a good example of how to use it: stuff example

Thinster
  • 46
  • 3
1

STUFF function and XMLPATH made the work.

SELECT id, 
    fecha, 
    tipo, 
    fuente, 
    origen, 
    estado, 
    gravedad, 
    cliente, 
    sectores, 
    datos, 
    idInforme, 
    STUFF((SELECT ',' + CAST(idDepartamento AS VARCHAR(5)) FROM InformeDepartamento WHERE idInforme = I.id FOR XML PATH('')),1,1,'') [PRUEBA]
FROM Informe I
INNER JOIN InformeDepartamento ID ON I.ID = ID.idInforme
GROUP BY id, fecha, tipo, fuente, origen, estado, gravedad, cliente, sectores, datos, idInforme
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
  • i appericiate that you tried of your own.But including so many column in group by often result in wrong result and poor perfromance.http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string – KumarHarsh Apr 10 '17 at 05:12