2011-05-27 83 views
1

我使用SQL Server 2008SQL循環和遞增

我有以下SQL得到今天和12月31日2012年間的所有日期我現在做的是先從值10000,並增加該值同樣所以12月31日我有15萬

Declare @projection table(d datetime, t decimal) 
Declare @d datetime 
Declare @t decimal(18, 2) 

set @d='20110527' 
set @t=100000 

While @d<='20121231' 
Begin 
Insert into @projection values (@d, @t) 
set @[email protected]+1 
End 
Select d as DateCol, t as TotalRevenue from @projection 

任何幫助,不勝感激

回答

2

這種線性插值t從10000到150000

Declare @projection table(d datetime, t decimal) 
Declare @d datetime, @d1 datetime, @d2 datetime 
Declare @t decimal(18,4), @t1 decimal(18, 4), @t2 decimal(18,4), @tincr decimal(18,4) 

set @d1='20110527' 
set @d2='20121231' 
set @t1=10000 
set @t2=150000 

Set @tincr = (@[email protected])/DATEDIFF(D, @d1, @d2) 

Set @d = @d1 
set @t = @t1 

While @d<[email protected] 
Begin 
Insert into @projection values (@d, @t) 
set @[email protected]+1 
Set @[email protected][email protected] 
End 
Select d as DateCol, t as TotalRevenue from @projection 

請注意,我將小數精度提高到4以使舍入誤差不顯着。

+0

這很棒,感謝您的快速響應。我的最終值現在是150002.但它必須是150000. – Dooie 2011-05-27 21:16:54

+0

將'decimal(18,2)'更改爲'decimal(18,4)'以消除舍入誤差。 – dmc 2011-05-27 21:20:13

+0

非常感謝你! – Dooie 2011-05-27 21:22:06