日期:2014-05-16 浏览次数:20646 次
create table tt(ID int,value int,type varchar(50));
insert into tt
select 1,1,'A' union all
select 2,2,'A' union all
select 3,3,'B' union all
select 4,4,'A' union all
select 5,5,'B' union all
select 6,6,'C' union all
select 7,7,'B' union all
select 8,8,'C' union all
select 9,9,'A' union all
select 10,10,'A' union all
select 11,11,'A';
with t1 as (
select *,rn=ROW_NUMBER()over(partition by type order by id)
from tt
)
select type,SUM(value) v
from t1
group by type,(rn-1)/3
having COUNT(1)=3
order by (rn-1)/3
create table gu
(ID int,value int,[type] varchar(5))
insert into gu
select 1,1,'A' union all
select 2,2,'A' union all
select 3,3,'B' union all
select 4,4,'A' union all
select 5,5,'B' union all
select 6,6,'C' union all
select 7,7,'B' union all
select 8,8,'C' union all
select 9,9,'A' union all
select 10,10,'A' union all
select 11,121,'A'
select [type],sum(value) '总和'
from
(select *,(row_number() over(partition by [type] order by ID)-1)/3 'rn'
from gu) t
group by [type],rn
having count(1)=3
/*
type 总和
----- -----------
A 7
B 15
A 140
(3 row(s) affected)
*