日期:2014-05-18 浏览次数:20608 次
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