SQLServer中没有MySQL中的group_concat函数,可以把分组的数据连接在一起。
后在网上查找,找到了可以实现此功能的方法,特此记录下。
SELECT
a,
stuff(
(SELECT '-' + b FROM tb WHERE a = t.a FOR xml path('') ),
1, 1, ''
)AS b from tb AS t
GROUP BY a;
先对a列进行分组,对分组中的b以Xml形式输出,再使用stuff将开关多出的,删掉。
示例SQL语句
select
--a.Id,
a.Name '产品名称',
--a.ParentId,
b.Name as '上级分类',
case a.IsOpenTask when '1' then '已开启' when '0' then '已关闭' end as '是否开启任务',
c.Name '进度阶段'
from tb_ServerType a
left join tb_ServerType b on b.id = a.ParentId
left join (
select ServerTypeId,
STUFF((select ' - ' + Name from tb_ServerTypeSchedule where ServerTypeId = t.ServerTypeId FOR xml path('')), 2, 1, '') Name
from tb_ServerTypeSchedule t
group by ServerTypeId
) c on c.ServerTypeId = a.Id
执行结果: