[SQL]把同一字段里的多行数据用一行显示

时间:2021-01-29 14:51:29
declare @t table(id int,num int)
insert @t
select 1,2 union all
select 2,4 union all
select 3,6
--select * from @t

----查询
declare @idList varchar(1000),@numList varchar(1000)
set @idList = ''
set @numList = ''
select 
@idList = case @idList when '' then '' else @idList + ',' end + rtrim(id),
@numList = case @numList when '' then '' else @numList + ',' end + rtrim(num)
from @t

select @idList as id,@numList as num

/*结果
id      num
------------------
1,2,3   2,4,6
*/