在列中获取CSV列表,保持列不同(SQL)

时间:2012-12-14 11:20:18

标签: sql sql-server

我需要帮助编写一个SQL查询,它可以让我得到我想要的结果。

我有一个文档上传功能,可以在多个位置为客户端上传文档。表结构简单,只有5列; FileID,FileName,Title,Description和LocationID。 如果用户上传3个位置的文档,则会在此表中输入3个条目。让我们说

FileID FileName    Title      Description      LocationID
1      File1       File1      Description 1    100
2      File1       File1      Description 1    21
4      File1       File1      Description 1    181

用户上传4个位置的另一个文件,输入数据,现在表格如下所示

FileID FileName    Title      Description      LocationID
1      File1.doc   File1      Description 1    100
2      File1.doc   File1      Description 1    21
4      File1.doc   File1      Description 1    181
5      File2.pdf   File2      Description 2    123
6      File2.pdf   File2      Description 2    12
7      File2.pdf   File2      Description 2    126
8      File2.pdf   File2      Description 2    100

现在我想要的结果是

FileName    Title      Description      LocationCSV
File1.doc   File1      Description 1    100, 21, 181
File2.pdf   File2      Description 2    123, 12, 126, 100

3 个答案:

答案 0 :(得分:5)

在SQL Server中,您可以使用FOR XML PATH

SELECT DISTINCT FileName,
  Title,
  Description,
  STUFF((SELECT ', ' + cast(LocationID as varchar(20))
         from yourtable m
         where p.FileName = m.FileName
         group by LocationID, fileid
         order by fileid
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') LocationCSV
from yourtable p

请参阅SQL Fiddle with Demo

使用FOR XML PATH的其他版本:

SELECT FileName,
  Title,
  Description, LEFT(LocationCSV , LEN(LocationCSV)-1) LocationCSV
FROM yourtable p
CROSS APPLY
(
    SELECT cast(LocationID as varchar(20)) + ','
    FROM yourtable m
    WHERE p.FileName = m.FileName
    FOR XML PATH('')
) m (LocationCSV)
group by FileName, Title, Description, LocationCSV

请参阅SQL Fiddle with Demo

结果:

|  FILENAME | TITLE |   DESCRIPTION |        LOCATIONCSV |
----------------------------------------------------------
| File1.doc | File1 | Description 1 |       100, 21, 181 |
| File2.pdf | File2 | Description 2 |  123, 12, 126, 100 |

答案 1 :(得分:3)

在MySQL中,您可以使用GROUP_CONCAT

select FileName,
       Title,
       Description, 
       group_concat(LocationID) as  LocationCSV 
from t group by FileName,Title,Description

答案 2 :(得分:0)

看看Bradc的答案。我喜欢这种方法来连接列。

Simulating group_concat MySQL function in Microsoft SQL Server 2005?