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

UNISCI tre tabelle e aggrega i dati da più righe per ogni riga DISTINCT in una colonna separata

Supponendo che tu non sia in grado di modificare le strutture di dati per eseguire una query più efficiente, questo funzionerà:

--Populate sample data
SELECT 1 as key1,       2  as key2 INTO #tbl1
UNION ALL SELECT 1,       5 
UNION ALL SELECT 1,       6 
UNION ALL SELECT 1,       4 
UNION ALL SELECT 1,       8 

SELECT 1  as key1,     'Desc short' as shortkeydesc INTO #tbl2

SELECT 1   as key1,    'Desc a'  as [description] INTO #tbl3
UNION ALL SELECT 1,       'Desc c' 
UNION ALL SELECT 1,       'Desc aa' 
UNION ALL SELECT 1,       'Desc tt' 

--Combine data into semi-colon separated lists
SELECT 
key1
,STUFF(
    (
    SELECT
      ';' + CAST(t2.key2 AS VARCHAR(10))
    FROM #tbl1 t2
    WHERE t2.key1 = tbl1.key1
    FOR XML PATH('')
    ), 1, 1, ''
  )
,STUFF(
    (
    SELECT
      ';' + tbl2.shortkeydesc
    FROM #tbl2 tbl2
    WHERE tbl2.key1 = tbl1.key1
    FOR XML PATH('')
    ), 1, 1, ''
  )
,STUFF(
    (
    SELECT
      ';' + tbl3.[description]
    FROM #tbl3 tbl3
    WHERE tbl3.key1 = tbl1.key1
    FOR XML PATH('')
    ), 1, 1, ''
  )
FROM #tbl1 tbl1
GROUP BY tbl1.key1