求合并相邻记录的语句解决思路
求合并相邻记录的语句
表记录如下:
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语句如何写?
------解决方案--------------------
表记录如下:
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] go create table [tb]([NAME] varchar(1),[QUANTITY] int) insert [tb] select 'a',1 union all select 'a',1 union all select 'b',2 union all select 'b',2 union all select 'a',1 union all select 'a',1 union all select 'b',2 union all select '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 QUANTITY FROM T2 GROUP BY NAME,GID ORDER BY MIN(RN) /** NAME QUANTITY ---- ----------- a 2 b 4 a 2 b 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