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

sammenkædning af enkelt kolonne i TSQL

Du kan bruge FOR XML PATH('') sådan her:

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

Resultater:

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. bedre måde at generere måneder/år tabel

  2. Hvordan opretter man indlejret SQL 2008-databasefil, hvis den ikke eksisterer?

  3. Forbinder F# til Salesforce.com

  4. Hvordan synkroniserer jeg to Oracle-databaser?