代码之家  ›  专栏  ›  技术社区  ›  shamim

如何在sql server中减去当前和以前的值

  •  0
  • shamim  · 技术社区  · 8 年前

    有一张表,需要减去前一列和当前金额。表值如下,需要为 Cal-Amount 柱

    Id Amount Cal-Amount
     1  100   0
     2  200   0
     3  400   0
     4  500   0
    

    卡尔量 带样本值的计算公式

    Id Amount Cal-Amount
     1  100   (0-100)=100
     2  200   (100-200)=100
     3  400   (200-400)=200
     4  500   (400-500)=100
    

    需要SQL语法减去列的当前值和上一个值

    5 回复  |  直到 8 年前
        1
  •  3
  •   Tim Biegeleisen    8 年前

    LAG 是使用SQL Server 2012或更高版本时的一个选项:

    SELECT
        Id,
        Amount,
        LAG(Amount, 1, 0) OVER (ORDER BY Id) - Amount AS [Cal-Amount]
    FROM yourTable;
    

    如果您使用的是早期版本的SQL Server,则可以使用自联接:

    SELECT
        Id,
        Amount,
        COALESCE(t2.Amount, 0) - t1.Amount AS [Cal-Amount]
    FROM yourTable t1
    LEFT JOIN yourTable t2
        ON t1.Id = t2.Id + 1;
    

    但是请注意,self join选项可能只在 Id 价值观是连续的。延迟可能是实现这一点的最有效方法,而且对于非顺序的 身份证件 值,只要顺序正确。

        2
  •  2
  •   George Menoutis    8 年前

    嗯,tim把我打到了lag(),下面是使用join的旧学派:

    select t.Id,t.Amount,t.Amount-isnull(t2.Amount,0) AS [Cal-Amount]
    from yourtable t
    left join yourtable t2 on t.id=t2.id+1
    
        3
  •  2
  •   marc_s MisterSmith    8 年前

    SQL Server 2012或更新版本:

    Select 
        ID, Amount, [Cal-Amount] = Amount - LAG(Amount, 1, 0) OVER (ORDER BY Id)
    From 
        table
    

    或

    Select 
        current.ID, Current.Amount, Current.Amount - Isnull(Prior.Amount, 0)
    from 
        table current 
    left join 
        table prior on current.id - 1 = prior.id
    
        4
  •  1
  •   marc_s MisterSmith    8 年前

    如果SQL Server=2012,则可以使用lag函数

    declare @t table (id int, amount1 int)
    
    insert into @t
    values (1, 100), (2, 200), (3, 400), (4, 500)
    
    select
        *, amount1 - LAG(amount1, 1, 0) over (order by id) as CalAmount 
    from 
        @t
    
        5
  •  0
  •   Yogesh Sharma    8 年前

    你也可以使用 apply :

    select t.*, t.Amount - coalesce(tt.Amount, 0) as CalAmount
    from table t outer apply (
         select top (1) *
         from table t1
         where t1.id < t.id
         order by t1.id desc
    ) tt;