MSSQL 通過FOR XML PATH 模仿MYSQL的 group_concat 函數,將紀錄值合並成字符串
;with tbl(id, s, sort) as
(
select 1, '廣東省', 3 union all
select 1, '廣州市', 2 union all
select 1, '越秀區', 1 union all
select 2, '北京市', 2 union all
select 2, '朝陽區', 1
)
select id,
(
stuff((select N','+ s
from tbl
where id=t.id
order by sort desc
FOR XML PATH('')), 1, 1, N'')
) as xmls
from tbl as t
group by t.id
order by t.id
stuff(字符串表達式1,開始位置,長度,字符串表達式2):在字符串表達式1中在指定的開始位置刪除指定長度的字符,並在指定的開始位置處插入字符串表達式2。返回新字符串。
select N','+ s from tbl FOR XML PATH('')將tbl 表的 S字段查詢出來,並用xml格式表示, 中間用 , 隔開。
PATH('') 括號中表示字段值前后添加何種標簽。
MYSQL 提供了直接分組合並的函數
select id, group_concat(s, ',') as s from tbl group by id