Sql Server String列concat和group by子句的使用

时间:2013-08-06 13:29:15

标签: sql-server group-by

我有一张这样的表:

Name          Address                             Matches
Tim Jones     1 London Road, London, W10EU        Peter Jones
Tim Jones     1 London Road, London, W10EU        Smith Jones
Tim Jones     1 London Road, London, W10EU        Tim Jones
Tim Jones     1 London Road, London, W10EU        S Singh
Jack Sons     10 West Street, London, W900U       John Graham
Jack Sons     10 West Street, London, W900U       Jack Sons

我想要这样的结果:

Name          Address                          Matches
Tim Jones     1 London Road, London, W10EU     Peter Jones,Smith johns,Tim Johns, S Singh
Jack Sons     10 West Street, London, W900U    John Graham, Jack Sons

它应该按名称,地址连接所有“匹配”列和组。 SQLServer08

1 个答案:

答案 0 :(得分:0)

Select distinct b.name, b.address,
               substring((Select ','+a.matches  AS [text()]
                From test15 a
                Where a.name=b.name and a.Address=b.Address
                ORDER BY a.name, a.address
                For XML PATH ('')),2, 1000) [Match]
         From dbo.test15 b