1

可能重复:
具有不同字符的 SQL Server 组连接

我需要一个关于 SELECT 的示例,其中输出是“,”分隔的字符串

例如SELECT (... something ...) name AS output FROM name_table

给我

output
-----------------------------
'Ann', 'Tom', 'Wilson', .....

您将如何在 SQL Server 2008 R2 中做到这一点?

谢谢!

4

1 回答 1

5

假设你有这样的模式,

CREATE TABLE Table1
    ([GROUP_ID] int, [PERSON_NAME] varchar(6));

INSERT INTO Table1
    ([GROUP_ID], [PERSON_NAME])
VALUES
    (1001, 'ALEX'),
    (1002, 'MATHEW'),
    (1001, 'GEORGE'),
    (1002, 'THOMAS'),
    (1001, 'JAMES');

创建一个类似这样的查询来产生一个逗号分隔的值,

SELECT
     GROUP_ID,
     STUFF(
         (SELECT ', ' + PERSON_NAME
          FROM Table1
          WHERE [GROUP_ID] = a.GROUP_ID
          FOR XML PATH (''))
          , 1, 1, '')  AS NamesList
FROM Table1 AS a
GROUP BY GROUP_ID
于 2012-12-07T03:18:48.207 回答