选择逗号分隔的邮政编码列表到ID

时间:2014-10-22 15:39:09

标签: sql sql-server sql-server-2008-r2

我有一套记录:

ID  Postcode

1   S43 4AX
1   S43 4PE
1   S43 4XE
1   S43 4XN
10  S43 4AB
10  S43 4AD
10  S43 4AG
10  S43 4AH
10  S43 4AJ
10  S43 4AL

我想从中选择:

ID    PostcodeList

1     S43 4AX, S43 4PE, S43 4XE, S43 4XN
10     S43 4AB,S43 4AD,S43 4AG,S43 4AH,S43 4AJ,S43 4AL

有一种简单的方法吗?

1 个答案:

答案 0 :(得分:0)

我使用了Michail Michailidis建议的代码来写这个

Select Distinct a.id, CAST((
          SELECT  T.postcode+','
          FROM mtable T
          WHERE A.id = T.id
          FOR XML PATH(''))as varchar(max)) as pclist
FROM mtable a