首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求合并相邻记录的语句解决思路

2012-01-18 
求合并相邻记录的语句表记录如下:NAMEQUANTITY----------------------------a1a1b2b2a1a1b2b2要求相邻记录

求合并相邻记录的语句
表记录如下:
  NAME QUANTITY
----------------------------
a 1
a 1
b 2
b 2
a 1
a 1
b 2
b 2
要求相邻记录name相同的字段合并数量,结果如下:
  NAME QUANTITY
----------------------------
a 2
b 4
a 2
b 4
sql语句如何写?

[解决办法]

SQL code
if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([NAME] varchar(1),[QUANTITY] int)insert [tb]select 'a',1 union allselect 'a',1 union allselect 'b',2 union allselect 'b',2 union allselect 'a',1 union allselect 'a',1 union allselect 'b',2 union allselect 'b',2;with t1 as(select rn=row_number() over(order by getdate()),* from [tb]),t2 as(select rn-(select count(1) from t1 where name=t.name and rn<=t.rn) gid,* from t1 t)SELECT NAME,SUM(QUANTITY) AS QUANTITYFROM T2GROUP BY NAME,GIDORDER BY MIN(RN)/**NAME QUANTITY---- -----------a    2b    4a    2b    4(4 行受影响)**/
[解决办法]
--tb为原来的表,tmp为加了序号的临时表
select id = identity(int,1,1) into tmp from tb

select name , sum(QUANTITY) QUANTITY from tmp group by name , (id-1) / 2
 

热点排行