SQL查找上一行和当前行之间的差异

时间:2014-04-21 15:17:09

标签: sql sql-server

我试图找到当前行和上一行之间的差异。但是,我收到以下错误消息:

  

多部分标识符" tableName"无法受约束。

不确定如何解决错误。

谢谢!

输出应如下所示:

columnOfNumbers     Difference
      1               NULL
      2               1
      3               1
      10              7
      12              2
      ....            ....

代码:

USE DATABASE;

WITH CTE AS 
(SELECT 
    ROW_NUMBER() OVER (PARTITION BY tableName ORDER BY columnOfNumbers) ROW,
    columnOfNumbers
    FROM tableName)
SELECT
    a.columnOfNumbers
FROM
    CTE a
    LEFT JOIN CTE b
    ON a.columnOfNumbers = b.columnOfNumbers AND a.ROW = b.ROW + 1

3 个答案:

答案 0 :(得分:20)

如果您使用的是SQL Server 2012+,则可以使用LAG。

 SELECT columnOfNumbers
       ,columnOfNumbers - LAG(columnOfNumbers, 1) OVER (ORDER BY columnOfNumbers)
   FROM tableName

注意:LAG的可选第三个参数是:

  

默认

     

当offset处的scalar_expression为NULL时返回的值。   如果未指定默认值,则返回NULL。默认可以   列,子查询或其他表达式,但它不能是分析   功能。 default必须与scalar_expression类型兼容。

答案 1 :(得分:16)

请参阅sqlFiddle

;WITH tblDifference AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY id) AS RowNumber, columnOfNumbers 
    FROM tableName
)

SELECT cur.columnOfNumbers, cur.columnOfNumbers - previous.columnOfNumbers
FROM tblDifference cur
LEFT OUTER JOIN tblDifference previous
ON cur.RowNumber = previous.RowNumber + 1

答案 2 :(得分:1)

我认为您不需要partition by声明:

WITH CTE AS (
      SELECT ROW_NUMBER() OVER (ORDER BY columnOfNumbers) as ROW,
             columnOfNumbers
      FROM tableName
     )
SELECT a.columnOfNumbers, a.columnOfNumbers - b.columnOfNumbers
FROM CTE a LEFT JOIN
     CTE b
     ON a.ROW = b.ROW + 1;

如果确实需要,您应该输入一个列名而不是表名。