Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

SQL 2005 Mesclar/concatenar várias linhas em uma coluna


tente isso:
set nocount on;
declare @t table (id char(36), x char(1))
insert into @t (id, x)
select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'A' union
select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'B' union
select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'C' union
select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'D' union
select '7ce953ca-a55b-4c55-a52c-9d6f012ea903' , 'E' union
select '7ce953ca-a55b-4c55-a52c-9d6f012ea903' , 'F'
set nocount off

SELECT p1.id, 
          stuff(
                   (SELECT
                        ' ' + x
                        FROM @t p2
                        WHERE p2.id=p1.id
                        ORDER BY id, x
                        FOR XML PATH('') 
                   )
                   ,1,1, ''
               ) AS YourValues
      FROM @t p1
      GROUP BY id

RESULTADO:
id                                   YourValues
------------------------------------ --------------
61E77D90-D53D-4E2E-A09E-9D6F012EB59C A B C D
7ce953ca-a55b-4c55-a52c-9d6f012ea903 E F

(2 row(s) affected)

EDITAR
com base no comentário do OP sobre isso precisar ser executado para uma consulta existente, tente isto:
;WITH YourBugQuery AS
(
    --replace this with your own query
    select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' AS ColID , 'A' AS ColX 
    union select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'B' 
    union select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'C' 
    union select '61E77D90-D53D-4E2E-A09E-9D6F012EB59C' , 'D' 
    union select '7ce953ca-a55b-4c55-a52c-9d6f012ea903' , 'E' 
    union select '7ce953ca-a55b-4c55-a52c-9d6f012ea903' , 'F'

)
SELECT p1.ColID, 
          stuff(
                   (SELECT
                        ' ' + ColX
                        FROM YourBugQuery p2
                        WHERE p2.ColID=p1.ColID
                        ORDER BY ColID, ColX
                        FOR XML PATH('') 
                   )
                   ,1,1, ''
               ) AS YourValues
      FROM YourBugQuery p1
      GROUP BY ColID

isso tem o mesmo conjunto de resultados exibido acima.