我有一张表presenters
我想找到主持人薪水之间的差异。喜欢(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"
这些是结果
但我想要以下结果
答案 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?