2

我有 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 中获得上述结果?

4

1 回答 1

5

SQL小提琴

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

结果

| FILENAME |                                    FILELOCATIONS |
---------------------------------------------------------------
|    file1 | \\server1\folder1\file1, \\server2\folder1\file1 |
|    file2 | \\server1\folder1\file2, \\server2\folder1\file2 |
于 2013-02-06T13:46:30.480 回答