当前位置: 代码迷 >> Sql Server >> 每隔5行1汇总
  详细解决方案

每隔5行1汇总

热度:26   发布时间:2016-04-24 18:28:35.0
每隔5行一汇总
表A 里的字段如下:

ID  期号        数量
1   2013-001     2
2   2013-001     1
3   2013-001     3
4   2013-001     2
5   2013-001     0
6   2013-001     2
7   2013-001     3
8   2013-001     6
9   2013-001     4
10  2013-001     5
11  2013-001     3
12  2013-001     2
13  2013-001     1
14  2013-001     2
.....

想要得到结果如下:字段 振幅=上次的平均值-本次的平均值



ID  期号        数量     平均值    最大值  最小值 振幅
1   2013-001     2
2   2013-001     1
3   2013-001     3
4   2013-001     2
5   2013-001     0        1.6       3       0     NULL
                     
6   2013-001     2
7   2013-001     3
8   2013-001     6
9   2013-001     4
10  2013-001     5 
                          4.0       6       2     2.4
11  2013-001     3
12  2013-001     2
13  2013-001     1
14  2013-001     2
                          2.0       3       1     2.0



请高人指点!谢谢了





------解决方案--------------------
id一定是连续的吗?如果没有用row_number生成一列连续的id

用这个   group by (id /5) 就每隔5行分段了。
------解决方案--------------------
引用:
请问这样该如何解决?


create table 表A
(ID int,期号 varchar(10),数量 int)
 
insert into 表A
 select 1,'2013-001',2 union all
 select 2,'2013-002',1 union all
 select 3,'2013-003',3 union all
 select 4,'2013-004',2 union all
 select 5,'2013-005',0 union all
 select 6,'2013-006',2 union all
 select 7,'2013-007',3 union all
 select 8,'2013-008',6 union all
 select 9,'2013-009',4 union all
 select 10,'2013-010',5 union all
 select 11,'2013-011',3 union all
 select 12,'2013-012',2 union all
 select 13,'2013-013',1 union all
 select 14,'2013-014',2
 

with t as
(select ID,期号,数量,(ID-1)/5+1 'rn' from 表A),
u as
(select max(ID) 'ID',
        cast(avg(cast(数量 as decimal(5,1))) as decimal(5,1)) 'avgqty',
        max(数量) 'maxqty',
        min(数量) 'minqty',
        row_number() over(order by rn) 'rn2'
 from t group by rn)
select c.ID,c.期号,c.数量,
       isnull(cast(d.avgqty as varchar(10)),'') '平均值',
       isnull(cast(d.maxqty as varchar(10)),'') '最大值',
       isnull(cast(d.minqty as varchar(10)),'') '最小值',
       case when d.ID is null then '' else cast(d.fq as varchar(10)) end '振幅'
 from t c
 left join 
 (select a.ID,a.avgqty,a.maxqty,a.minqty,abs(b.avgqty-a.avgqty) 'fq'
  from u a
  left join u b on a.rn2=b.rn2+1) d on c.ID=d.ID
 
/*
ID          期号         数量          平均值        最大值        最小值        振幅
  相关解决方案