我在SQL Server 2008中有一个数据表,其中包含应用程序名称和部门,其中安装了该数据。
我想从安装App的每个部门的记录返回到每个应用程序的单个单元格中连接或组合的所有部门。
这可能吗?谢谢!
答案 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 ║
╚══════════╩══════════════════════════╝