简体   繁体   English

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

[英]How to create two new columns based on previous rows in SQL Server?

Suppose I have this table(sort by the Date ): 假设我有此表(按Date排序):

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

And I want to create two new columns. 我想创建两个新列。 Something like this 像这样

  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

Start : 开始

the first Start is the first Amount , 第一个Start是第一个Amount

the next one is based on the first Amount - Hours 下一个基于第一个金额 - 小时

and so on 等等

End is basically the next row for Start 结束基本上是开始的下一行

Is there a way to do this? 有没有办法做到这一点?

You can use a running sum to do this. 您可以使用sum来执行此操作。 Then a lag to get the previous end on to the current row. 然后是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

Simply subtract the Running Total of those hours from the Amount: 只需从金额中减去这些小时的运行总计

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM