使用T-SQL中行的先前值计算值

The*_*Guy 8 t-sql sql-server

我得到了下表,并希望使用sql中前一行中相同列(Column2)的值计算每行的Column2值,而不使用cursor或while循环.

Id   Date             Column1    Column2
1    01/01/2011       5          5 => Same as Column1
2    02/01/2011       2          18 => (1 + (value of Column2 from the previous row)) * (1 + (Value of Column1 from the current row)) i.e. (1+5)*(1+2)
3    03/01/2011       3          76 => (1+18)*(1+3) = 19*4
and so on
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?


Joe*_*lli 5

假设至少SQL Server 2005用于递归CTE:

;with cteCalculation as (
    select t.Id, t.Date, t.Column1, t.Column1 as Column2
        from YourTable t
        where t.Id = 1
    union all
    select t.Id, t.Date, t.Column1, (1+t.Column1)*(1+c.Column2) as Column2
        from YourTable t
            inner join cteCalculation c
                on t.Id-1 = c.id
)
select c.Id, c.Date, c.Column1, c.Column2
    from cteCalculation c
Run Code Online (Sandbox Code Playgroud)

  • @mellamokb我认为你可以使用一个带有row_num()的cluase(按...排序),然后在递归CTE中引用它,但我不确定,这里没有SQL.您还可以查看lead()和lag().实际上,如果你使用铅和滞后,你不需要CTE,它们也会更快. (4认同)