连接两个表并连接单个字段的多行

时间:2014-05-05 22:42:12

标签: sql sql-server tsql

查询:

CREATE TABLE #Temp1 (ID int)
CREATE TABLE #Temp2 (ID int, Value varchar(10))

INSERT INTO #Temp1 (ID)
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3

INSERT INTO #Temp2(ID, Value)
SELECT 1,'One-One'
UNION ALL
SELECT 1,'One-Two'
UNION ALL
SELECT 1,'One-One'
UNION ALL
SELECT 2,'Two-One'
UNION ALL
SELECT 2,'Two-Two'
UNION ALL
SELECT 2,'Two-One'

SELECT T1.ID, T2.Value FROM #Temp1 T1 INNER JOIN #Temp2 T2 ON T1.ID = T2.ID

DROP TABLE #Temp1
DROP TABLE #Temp2

当前输出:

ID  Value
1   One-One
1   One-Two
1   One-One
2   Two-One
2   Two-Two
2   Two-One

期望的输出:

ID  Values
1,  One-One, One-Two, One-One
2,  Two-One, Two-Two, Two-One

我想在一个关键列ID上加入两个表#Table1和#Tabl2,从第二个表中获取Value字段......但是在一行中(如所需的输出所示)。

如何(如果可能)我可以实现所需的输出?

谢谢

2 个答案:

答案 0 :(得分:5)

SELECT T1.ID,
      STUFF((SELECT ', ' + T2.Value
             FROM   #Temp2 T2 
             WHERE  T1.ID = T2.ID
             FOR XML PATH(''),TYPE)
             .value('.','NVARCHAR(MAX)'),1,2,'') AS Value
FROM #Temp1 T1 
GROUP BY T1.ID

结果集

╔════╦═══════════════════════════╗
║ ID ║           Value           ║
╠════╬═══════════════════════════╣
║  1 ║ One-One, One-Two, One-One ║
║  2 ║ Two-One, Two-Two, Two-One ║
╚════╩═══════════════════════════╝

答案 1 :(得分:1)

试试这个:

SELECT Id, STUFF(A.Value, 1, 2, '') [Values] FROM #Temp1 T1
CROSS APPLY 
(
   SELECT ', ' + Value FROM #Temp2 T2 WHERE T1.ID = T2.ID FOR XML PATH('')
) A(Value)
WHERE A.Value IS NOT NULL