sql >> Databasteknik >  >> RDS >> Sqlserver

SQL 2005 Slå samman / sammanfoga flera rader till en kolumn

prova detta:

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

UTGÅNG:

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

(2 row(s) affected)

REDIGERA
baserat på OP:s kommentar om att detta måste köras för en befintlig fråga, prova detta:

;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

detta har samma resultat som visas ovan.



  1. Problem när användaren matar in data i sql-kommandot

  2. hämta data grupperade efter månad med mysql-intervall

  3. Hur ofta ska jag stänga databasanslutningar?

  4. SQL Server-isoleringsnivåer:A-serien