sql >> Databasteknik >  >> RDS >> Sqlserver

sammanlänkning av en kolumn i TSQL

Du kan använda FOR XML PATH('') så här:

DECLARE @TestData TABLE
(
     address_desc NVARCHAR(100) NOT NULL
    ,people_id UNIQUEIDENTIFIER NOT NULL
);

INSERT  @TestData 
SELECT  'Murfreesboro, TN  37130',              'F15D1135-9947-4F66-B778-00E43EC44B9E'
UNION ALL
SELECT  '11 Mohawk Rd., Burlington, MA 01803',  'C561918F-C2E9-4507-BD7C-00FB688D2D6E'
UNION ALL
SELECT  'Unknown, UN  00000',                   'C561918F-C2E9-4507-BD7C-00FB688D2D6E'
UNION ALL
SELECT  'Memphis, TN  38133',                   '8ED8C601-5D35-4EB7-9217-012905D6E9F1'
UNION ALL
SELECT  '44 Maverick St., Fitchburg, MA',       '8ED8C601-5D35-4EB7-9217-012905D6E9F1';

SELECT  a.people_id,
    (SELECT SUBSTRING(
        (SELECT ';'+b.address_desc
        FROM    @TestData b 
        WHERE   a.people_id = b.people_id
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
        ,2
        ,4000)
    ) GROUP_CONCATENATE
FROM    @TestData a
GROUP BY a.people_id

Resultat:

people_id                            GROUP_CONCATENATE
------------------------------------ ------------------------------------------------------
F15D1135-9947-4F66-B778-00E43EC44B9E Murfreesboro, TN  37130
C561918F-C2E9-4507-BD7C-00FB688D2D6E 11 Mohawk Rd., Burlington, MA 01803;Unknown, UN  00000
8ED8C601-5D35-4EB7-9217-012905D6E9F1 Memphis, TN  38133;44 Maverick St., Fitchburg, MA



  1. Importera .frm- och .opt-filer till MySQL

  2. SQLiteException ingen sådan tabell:ItemTable under kompilering:Select_id,.... from ItemTable

  3. Uppgradera PostgreSQL JSON-kolumnen till JSONB?

  4. MySQL Slå samman två tabeller med kommaseparerade värden