我有sql查询来获取文件的位置
select FileName, FileLocation from tblFile
和
之类的数据FileName FileLocation
file1 \\server1\folder1\file1
file1 \\server2\folder1\file1
file2 \\server1\folder1\file2
file2 \\server2\folder1\file2
我想获得如下数据:
FileName FileLocations
file1 \\server1\folder1\file1, \\server2\folder1\file1
file2 \\server1\folder1\file2, \\server2\folder1\file2
如何在sql server中获得以上结果?
答案 0 :(得分:5)
MS SQL Server 2008架构设置:
create table tblFile
(
FileName varchar(10),
FileLocation varchar(30)
)
insert into tblFile values
('file1', '\\server1\folder1\file1'),
('file1', '\\server2\folder1\file1'),
('file2', '\\server1\folder1\file2'),
('file2', '\\server2\folder1\file2')
查询1 :
select T1.FileName,
(
select ', '+T2.FileLocation
from tblFile as T2
where T1.FileName = T2.FileName
for xml path(''), type
).value('substring(text()[1], 3)', 'varchar(max)') as FileLocations
from tblFile as T1
group by T1.FileName
<强> Results 强>:
| FILENAME | FILELOCATIONS |
---------------------------------------------------------------
| file1 | \\server1\folder1\file1, \\server2\folder1\file1 |
| file2 | \\server1\folder1\file2, \\server2\folder1\file2 |