T-SQL如何在group by语句中连接前n行的字符串字段

时间:2014-12-25 11:43:13

标签: sql sql-server tsql

我有一张表格如下:

FileHash              FilePath
1                     A.txt
3                     e.txt
3                     f.txt
3                     g.txt
3                     h.txt
2                     B.txt
2                     c.txt

在T-SQL中,如何连接每个FileHash的前3 FilePath,如下所示:

FileHash              FilePath
1                     A.txt
2                     B.txt, C.txt
3                     e.txt, f.txt, g.txt

1 个答案:

答案 0 :(得分:1)

一种方法:

WITH files
     AS (SELECT DISTINCT FileHash
         FROM   dbo.test)
SELECT FileHash,
       Stuff((SELECT ', ' + FilePath
              FROM   dbo.Test AS fp
              WHERE  fp.FileHash = files.FileHash
              FOR XML PATH('')), 1, 2, '') AS FilePath
FROM   files;