简体   繁体   English

如何在下一行SQL Server中减去列值

[英]How to subtract column value in next row SQL server

i want to subtract values in same column, this subtraction should be done on very next row. 我想减去同一列中的值,这种相减应在下一行进行。

具有2列的表数据

i want to subtract record in row 1 and row 2 and so on (row2 x - row1 x) 我想减去第1行和第2行中的记录,依此类推(row2 x-row1 x)

You can use LEAD : 您可以使用LEAD

SELECT x
      ,lead(x, 1, 0) OVER (ORDER BY id) - x
From myTable;

You need to order the rows. 您需要对行进行排序。 In above example I have done this by ID but you can use whatever you have. 在上面的示例中,我已按ID进行了此操作,但是您可以使用任何已有的东西。

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

DEMO 演示

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

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