日期:2014-05-16  浏览次数:20587 次

SQL语句-- 按类型每3个记录求一次总和
格式如下:

ID    value    type
1        1          A
2         2          A
3        3          B
4        4           A
5        5           B
6        6          C
7        7           B
8        8          C
9        9          A
10      10       A
11      121     A
我想实现按分类,每隔3条记录求一次总和,显示结果应为如下所示:
  1+2+4=7     A
  9+10+11=30  A
   3+5+7=15
但是 不够3个的不总和,例如C。
希望得到大家的帮助,非常感谢大家

------解决方案--------------------
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)
*