[英]How to subtract column value in next row SQL server
Here is other dynamic way is to use CTE
with the help of row_number
function will assign ranking to each rows. 这是另一种动态方式,是在
row_number
函数的帮助下使用CTE
将排名分配给每一行。
;WITH CTE AS
(
SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) RN FROM <table_name>
),
CTE1 AS
(
SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) RN FROM <table_name>
)
SELECT C1.X - C.X [x] FROM CTE C
INNER JOIN CTE1 C1 ON C1.RN = C.RN+1
Explanation: The CTE
will grab all of your records and apply a row number for each unique entry. 说明:
CTE
将获取您的所有记录,并为每个唯一条目应用行号。 Each additional entry will get an incrementing number. 每个其他条目将获得一个递增的数字。
You need an ID on your table to auto join your table. 您需要在表上有一个ID才能自动加入表。 Use modulo operator to select half part with alias A an second part with alias B :
使用取模运算符选择别名A的一半和别名B的第二部分:
select
A.*,
B.*,
B.X-A.X as DELTA
from
theTable A inner theTable B on
A.ID+1=B.ID
where
A.ID % 2 = 1
EDIT, if you don't have an ID you an order clause
to determine it : 编辑,如果您没有ID,则可以使用
order clause
来确定它:
with order_table (
select
ROW_NUMBER ()
OVER ( order by ??? ) as ID,
*
from
theTable
)
select
A.*,
B.*,
B.X-A.X as DELTA
from
order_table A inner order_table B on
A.ID+1=B.ID
where
A.ID % 2 = 1
replace `???` by your criteria.
WARNING : Data in a sql table is not ordered. 警告 :sql表中的数据未排序。 You can't easly preserve the insertion order without a specific columns like ID or Timesstamp...
没有ID或Timesstamp之类的特定列,您将无法轻松保留插入顺序。
You can use ANSI
standard OLAP
functions as below to get your desired result. 您可以如下使用
ANSI
标准OLAP
函数来获得所需的结果。
SELECT x,
min(x) over(
ORDER BY id ROWS BETWEEN 1 following AND 1 following) - x AS RESULT
FROM table1;
The above query sorts the result by id
and subtract row n
from row n + 1
and displays result along with row n
上面的查询按
id
对结果进行排序,并从第n + 1
行中减去第n
行,并将结果与第n
行一起显示
Sample data along with Result: 样本数据以及结果:
x RESULT
-----------------------------------
318963.0000000000 -95.9999999990
318867.0000000010 -128.0000000000
318739.0000000010 128.0000000000
318867.0000000010 NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.