当前位置: 移动技术网 > IT编程>数据库>MSSQL > Sql Server:多行合并成一行,并做分组统计的两个方法

Sql Server:多行合并成一行,并做分组统计的两个方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

云南省公务员考试报名人数,蛇胆疮图片,胡莱战国

复制代码 代码如下:

--创建 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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网