简体   繁体   English

使用上一行中的值来计算下一行中的值

[英]Using a value from a previous row to calculate a value in the next row

I am trying to create a report that pulls the date from a previous row, does some calculation and then displays the answer on the row below that row. 我正在尝试创建一个报告,该报告从上一行获取日期,进行一些计算,然后在该行下方的行上显示答案。 The column in question is "Time Spent". 有问题的列是“花费的时间”。

Eg I have 3 rows. 例如,我有3行。

+=====+===============+============+====+
|name |  DatCompleted | Time Spent | idx|
+=====+===============+============+====+
|  A  |    1/1/17     | NULL       | 0  |
+-----+---------------+------------+----+
|  B  |    11/1/17    | 10 days    | 1  |
+-----+---------------+------------+----+
|  C  |    20/1/17    | 9 days     | 2  |
+=====+===============+============+====+

Time Spent C = DatCompleted of C - DateCompleted of B 花费的时间C = D的D完成-B的日期完成

Apart from using a crazy loop and using row x row instead of set I can't see how I would complete this. 除了使用疯狂循环并使用row x row而不是set之外,我看不到如何完成此操作。 Has anyone ever used this logic before in SQL? 有没有人曾经在SQL中使用过这种逻辑? If how did you go about this? 如果你是怎么做的?

Thanks in advance! 提前致谢!

Most databases support the ANSI standard LAG() function. 大多数数据库都支持ANSI标准LAG()函数。 Date functions differ depending on the database, but something like this: 日期函数因数据库而异,但类似这样:

select t.*,
       (DateCompleted - lag(DateCompleted) over (order by DateCompleted)) as TimeSpent
from t;

In SQL Server, you would use datediff() : 在SQL Server中,您将使用datediff()

select t.*,
       datediff(day,
                lag(DateCompleted) over (order by DateCompleted), 
                DateCompleted
               ) as TimeSpent
from t;

You can do this by using ROW number syntax is 您可以通过使用ROW数字语法做到这一点

ROW_NUMBER ( ) OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause)

For reference you can use ROW_NUMBER 供参考,您可以使用ROW_NUMBER

You have an index already (similar to rownumber above). 您已经有一个索引(类似于上面的行号)。 Join to itself. 加入自己。

Select table1.*
   ,TimeSpent=DateDiff("d",table1.DateCompleted,copy.DateCompleted)
from table1
   join table1 copy on table.idx=copy.idx-1

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

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