Table_One:
+---------+----------+
| USER_ID| name |
+---------+----------+
| 2 | Rick |
+---------+----------+
Table_Two
+---------+----------+----------+
| t2_ID | sport | USER_ID |
+---------+----------+----------+
| 32 | football | 2 |
+---------+----------+----------+
| 33 | baseball | 2 |
+---------+----------+----------+
我希望得到的结果如下:
+---------+----------+--------------------+
| 2 | Rick | Football, Baseball |
+---------+----------+--------------------+
我不明白如何将这样一个INNER JOIN的多行合并为一列。
SELECT Table_One.* FROM Table_One LEFT JOIN Table_Two ON Table_Two.USER_ID = Table_One.USER_ID
我将结果作为单独的行:
+---------+----------+----------+
| 2 | Rick | football |
+---------+----------+----------+
| 2 | Rick | baseball |
+---------+----------+----------+
谢谢所有阅读此书的人。
答案 0 :(得分:2)
在进行任何评论/编辑之前,此问题基于标签回答。
您可以使用FOR XML PATH()
子句:
SELECT to.*,
STUFF( (SELECT DISTINCT ', ' +tt.sport
FROM Table_Two tt
WHERE tt.USER_ID = to.USER_ID
FOR XML PATH('')
), 1, 1, ''
) AS Sports
FROM Table_One to;