Sql Server:多行合并成一行,并做分组统计的两个方法
云南省公务员考试报名人数,蛇胆疮图片,胡莱战国
--创建 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
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
详解SQL游标的用法
类型: 1.普通游标 只有next操作 2.滚动游标 有多种操作1.普通游标declare @username varchar(20),@userid varc...
[阅读全文]
-
-
-
-
-
-
-
-
-
网友评论