SQL语句- 按部类每3个记录求一次总和
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。
希望得到大家的帮助,非常感谢大家
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
格式如下:
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)
*/
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-28 14:19:34
-- Version:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[value] int,[type] varchar(1))
insert [tb]
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'
--------------开始查询--------------------------
;
WITH cte
AS (SELECT
*, growid = ROW_NUMBER() OVER (PARTITION BY type ORDER BY id)
FROM
tb)