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

时间:2016-09-04 00:31:27

标签: sql sql-server sql-server-2012

我有一张表presenters

enter image description here

我想找到主持人薪水之间的差异。喜欢(Jason - Vicki,Jason - Tiff,Vicki - Tiff)。

我有以下代码

SELECT 
    P2.PNRFNAME, P1.PNRFNAME AS "pnrfname",
    P2.SALARY_YEARLY - P1.SALARY_YEARLY AS "salary difference" 
FROM 
    PRESENTERS P2
JOIN 
    PRESENTERS P1 ON P2.PNRFNAME > P1.PNRFNAME
ORDER BY 
    "salary difference"

这些是结果

enter image description here

但我想要以下结果

enter image description here

2 个答案:

答案 0 :(得分:2)

如果您的行按PRESENTERID排序,而不是P2.PNRFNAME > P1.PNRFNAME,则可以使用PRESENTERID

尝试;

SELECT P2.PNRFNAME ,P1.PNRFNAME AS "pnrfname" , P2.SALARY_YEARLY - P1.SALARY_YEARLY AS "salary difference" 
FROM PRESENTERS P2
INNER JOIN PRESENTERS P1
ON P2.PRESENTERID> P1.PRESENTERID
ORDER BY P2.PRESENTERID, P1.PRESENTERID

答案 1 :(得分:0)

您可以尝试以下代码:

WITH CTE
AS (
    SELECT rownum = ROW_NUMBER() OVER (
            ORDER BY PNRFNAME
            )
        ,PNRFNAME
        ,SALARY_YEARLY
    FROM PRESENTERS
    )
SELECT prev.PNRFNAME PreviousValue
    ,CTE.PNRFNAME
    ,prev.SALARY_YEARLY - CTE.SALARY_YEARLY AS SALARY_DIFF
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
GO

来源:How to Access the Previous Row and Next Row value in SELECT statement?