复制代码 代码如下:
–创建 test 表 ,插入数据
create table test(code varchar(50), [values] varchar(10),[count] int)
insert test select ‘001’, ‘aa’,1
union all select ‘001’, ‘bb’,2
union all select ‘002’, ‘aaa’,4
union all select ‘002’, ‘bbb’,5
union all select ‘002’, ‘ccc’,3;
–方法一
–将多行合并成一行,并做分组统计
select code,
[values] =
stuff(b.[values].value(‘/r[1]’, ‘nvarchar(max)’),
,
,
”),[count]
from (select code,sum([count]) as [count]
from test
group by code) a
cross apply (
select [values] =(
select n’,’ + [values] from test
where code = a.code
for xml path(”), root(‘r’), type
)
) b;
–方法二
—sql2005中的新解法 使用xml
select code, data=stuff((select ‘,’+[values] from test t where code=t1.code for xml path(”)), 1, 1, ”),sum([count]) as [count]
from test t1
group by code
–查询结果
–001 aa,bb 3
–002 aaa,bbb,ccc 12
drop table test