读书人

请问一个比较复杂的统计求和语句

发布时间: 2012-12-31 11:57:52 作者: rapoo

请教一个比较复杂的统计求和语句
概要是每相邻两条记录相关子段计算出一个值,最后再求和
表类似下面

id L1 L2
1 1.1 3.3
2 2.3 6.5
3 3.6 7.7
.................


前两条记录根据L1,L2数据用某公式求出一个值,然后第二三条记录也求出一个值,依次类推....
最后将这些值相加,该如何做呢?


[解决办法]

----------------------------
-- Author :TravyLee(物是人非事事休,欲语泪先流!)
-- Date :2012-12-14 10:09:00
-- Version:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
--Jul 9 2008 14:43:34
--Copyright (c) 1988-2008 Microsoft Corporation
--Developer Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go
create table [test]([id] int,[L1] numeric(8,2),[L2] numeric(8,2))
insert [test]
select 1,1.1,3.3 union all
select 2,2.3,6.5 union all
select 3,3.6,7.7

select * from [test]
go

--我不知道你说的公式是什么 这里我当求乘积

;with t
as(
select *,cast(L1*L2 as numeric(8,2)) as CJ from test where [id]=1
union all
select a.*,cast(b.CJ+a.L1*a.L2 as numeric(8,2))from test a inner join t b on a.id=b.id+1
)
select * from t

/*
id L1 L2 CJ
----------- --------------------------------------- --------------------------------------- ---------------------------------------
1 1.10 3.30 3.63
2 2.30 6.50 18.58
3 3.60 7.70 46.30



(3 行受影响)


*/

读书人网 >SQL Server

热点推荐