将SQL结果整合到单个单元格中

时间:2014-02-18 22:22:55

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

我在SQL Server 2008中有一个数据表,其中包含应用程序名称和部门,其中安装了该数据。

我想从安装App的每个部门的记录返回到每个应用程序的单个单元格中连接或组合的所有部门。

这可能吗?谢谢!

enter image description here

1 个答案:

答案 0 :(得分:0)

测试数据

DECLARE @TABLE TABLE([App Name] VARCHAR(20),[Department Install] VARCHAR(20))
INSERT INTO @TABLE VALUES
('Office','Finance'),('Office','Accounting'),('Acrobat','Finance'),
('Acrobat','Accounting'),('Acrobat','HR')

<强>查询

SELECT t.[App Name]
      ,STUFF((SELECT ', ' + [Department Install] [text()]
              FROM @TABLE
              WHERE [App Name] = t.[App Name]
              FOR XML PATH(''), TYPE
              ).value('.','NVARCHAR(MAX)'),1 ,2,' ') AS [Department Install]
FROM @TABLE t
GROUP BY t.[App Name]

结果集

╔══════════╦══════════════════════════╗
║ App Name ║    Department Install    ║
╠══════════╬══════════════════════════╣
║ Acrobat  ║  Finance, Accounting, HR ║
║ Office   ║  Finance, Accounting     ║
╚══════════╩══════════════════════════╝