如何在一列中转换外键值?

时间:2016-07-14 10:43:12

标签: sql-server tsql

我正在使用SQL Server 2008 R2(SP2)数据库。 对于客户数据和他的兴趣,我有两个这样的表:

表名:客户

+----+----------+---------+
| Id | Name     | Surname |
+----+----------+---------+
| 1  | Mario    | Rossi   |
+----+----------+---------+
| 2  | Giuseppe | Verdi   |
+----+----------+---------+

表名:客户利益

+------------+----------+
| CustomerId | Interest |
+------------+----------+
| 1          | IT       |
+------------+----------+
| 1          | Football |
+------------+----------+
| 1          | Basket   |
+------------+----------+
| 2          | Basket   |
+------------+----------+
| 2          | Bonsai   |
+------------+----------+

我需要为数据提取创建一个SQL语句。输出结果必须如下:

+----+----------+---------+-----------------------+
| Id | Name     | Surname | Interests             |
+----+----------+---------+-----------------------+
| 1  | Mario    | Rossi   | IT; Football; Basket; |
+----+----------+---------+-----------------------+
| 2  | Giuseppe | Verdi   | Basket; Bonsai;       |
+----+----------+---------+-----------------------+

从本质上讲,我会在一列中将所有客户的兴趣以分号分隔。

我怎样才能获得这个?

谢谢, 马可

1 个答案:

答案 0 :(得分:0)

尝试以下查询

SELECT
    Id,
    Name,
    Surname,
    (
        SELECT 
            CI.Interest + '; '
        FROM                
            CustomerInterests CI
        WHERE 
            CI.CustomerId = C.ID
        FOR XML PATH ('')
    ) AS Interest 
FROM
    Customer C