从SELECT语句构建字符串

时间:2012-12-07 03:16:28

标签: sql sql-server-2008 sql-server-2008-r2

  

可能重复:
  SQL Server Group Concat with Different characters

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

e.g。 SELECT (... something ...) name AS output FROM name_table

给了我

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

您将如何在SQL Server 2008 R2中执行此操作?

谢谢!

1 个答案:

答案 0 :(得分:4)

假设您有这样的架构,

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