如何根据SQL Server中的先前行创建两个新列?

时间:2018-10-09 17:22:49

标签: sql sql-server

假设我有这张桌子(按日期排序):

  Hours Amount Date
1 2     20     1
2 1     20     3
3 6     20     10
4 3     20     20

我想创建两个新列。像这样

  Hours Amount Start End Time
1 2     20     20    18  1
2 1     20     18    17  3
3 6     20     17    11  10
4 3     20     11    7   20

开始

  

第一个开始是第一个金额

     

下一个基于第一个金额-小时

     

以此类推

结束基本上是开始

的下一行

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以使用正在运行的sum来执行此操作。然后使用lag将前一个end移至当前行。

select t.*,coalesce(lag(end) over(order by date),start) as start
from (select hours,amount,date,amount-sum(hours) over(order by date) as end
      from tbl
      ) t

答案 1 :(得分:0)

只需从金额中减去这些小时的运行总计

select t.*
  ,amount - cumulative_hours as end
  ,amount - cumulative_hours + hours as start
from
 (
   select hours
     ,amount
     ,date
     ,sum(hours) over(order by date rows unbounded preceding) as cumulative_hours
   from tab
  ) t