表记录如下:
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