Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL 2005 Unisci/concatena più righe in una colonna

prova questo:

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

USCITA:

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

(2 row(s) affected)

MODIFICA
in base al commento di OP su questa necessità di essere eseguita per una query esistente, prova questo:

;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

questo ha gli stessi risultati impostati come mostrato sopra.