日期:2014-05-19  浏览次数:20949 次

数据库中的循环问题
数据库中有10个表,分别为t1,t2,t3......它们都含有x列下面要做的是表中的x列进行运算
要实现一个循环功能(t2.x-t1.x)+(t3.x-t2.x)+(t4.x-t3.x)........
可理解为   t+=t[i+1].x-t[i].x,其中t,i初始值为0;
请问这个循环式子在数据库中不知怎么实现,用ADO.NET,sql语言应该怎么写?

------解决方案--------------------
--为避免只有一天的数据时查不到结果,又修改了一下:

create table #pointInfo
(
pointId int identity(1,1),
pointName nvarchar(20)
)

create table #pointDaily
(
id int identity(1,1),
pointId int,
[date] datetime,
x numeric(18,4),
y numeric(18,4),
z numeric(18,4)
)

insert into #pointInfo(pointName)
select 'A ' union all
select 'B ' union all
select 'C '

insert into #pointDaily(pointId, [date], x, y, z)
select 1, '2007-01-01 ', 0.10, 0.20, 0.30 union all
select 1, '2007-01-02 ', 0.110, 0.120, 0.310 union all
select 1, '2007-01-03 ', 0.310, 0.230, 0.330 union all
select 2, '2007-01-01 ', 0.510, 0.520, 0.30 union all
select 2, '2007-01-02 ', 0.150, 0.250, 0.350 union all
select 2, '2007-01-03 ', 0.170, 0.280, 0.380 union all
select 3, '2007-01-01 ', 0.150, 0.250, 0.350

select a.pointId, a.[date] as st, b.[date] as et,
(b.x - a.x) as xchange, (b.y - a.y) as ychange, (b.z - a.z) as zchange
into #temp
from #pointDaily a
inner join #pointDaily b on a.pointId = b.pointId and datediff(dd, a.[date], b.[date]) = 1

select *
into #ret
from
(
select pointId, st, et, xchange, ychange, zchange
from #temp
union all
select pointId, [date],[date], x, y, z
from #pointDaily a
where not exists (select 1 from #temp where pointId = a.pointId )
) x

select b.pointname, a.st, a.et, a.xchange, a.ychange, a.zchange
from #ret a
left join #pointInfo b on a.pointId = b.pointId

drop table #pointInfo, #pointDaily, #temp, #ret