适用于SQL Server的GROUP_CONCAT

时间:2016-03-22 13:05:59

标签: sql-server aggregate

我做了一些搜索,可以看到之前已经多次询问过这个问题,但我似乎无法将解决方案转化为我自己的工作示例。有人能指出我正确的方向吗?

我有三个数据库表,如下所示

People
+-------+------------+
|  uid  |   person   |
+-------+------------+
|   1   | Tom        |
+-------+------------+
|   2   | Dick       |
+-------+------------+
|   3   | Harry      |
+-------+------------+
|   4   | Peter      |
+-------+------------+
|   5   | Paul       |
+-------+------------+

Sports
+---------+----------------+
|   gid   |   group_name   |
+---------+----------------+
|    1    | Dancing        |
+---------+----------------+
|    2    | Golf           |
+---------+----------------+
|    3    | Football       |
+---------+----------------+
|    4    | Tennis         |
+---------+----------------+
|    5    | Squash         |
+---------+----------------+

Teams
+---------+---------+
|   gid   |   uid   |
+---------+---------+
|    1    |    1    |
+---------+---------+
|    2    |    1    |
+---------+---------+
|    3    |    1    |
+---------+---------+
|    1    |    2    |
+---------+---------+
|    2    |    2    |
+---------+---------+
|    3    |    2    |
+---------+---------+
|    4    |    2    |
+---------+---------+
|    2    |    3    |
+---------+---------+
|    1    |    4    |
+---------+---------+
|    5    |    4    |
+---------+---------+
|    1    |    5    |
+---------+---------+
|    4    |    5    |
+---------+---------+
|    3    |    5    |
+---------+---------+

我想要一个SELECT查询,每个人返回一行,列出他们所做的所有运动(以逗号分隔)。在上面的示例中,结果将是

+-------+------------+----------------------------------+
|  uid  |   person   |   group_name                     |
+-------+------------+----------------------------------+
|   1   | Tom        | Dancing, Golf, Football          |
+-------+------------+----------------------------------+
|   2   | Dick       | Dancing, Golf, Football, Tennis  |
+-------+------------+----------------------------------+
|   3   | Harry      | Golf                             |
+-------+------------+----------------------------------+
|   4   | Peter      | Dancing, Squash                  |
+-------+------------+----------------------------------+
|   5   | Paul       | Tennis, Football                 |
+-------+------------+----------------------------------+

在MYSQL中,我会使用GROUP_CONCAT,但在这个实例中我使用的是SQL SERVER。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

SELECT p.uid, p.person,
       stuff (g.group_name, 1, 1, '') as group_name
FROM   People p
CROSS APPLY
(
    SELECT ',' + s.group_name
    FROM   Teams t
           INNER JOIN Sports s ON t.gid = s.gid
    WHERE  t.uid = p.uid
    ORDER BY s.group_name
    FOR XML PATH ('')
) g (group_name)