2016-08-24 188 views
0

我還是SQL Server的新手,我需要幫助解決這個問題。SQL Server查找行之間的差異

我需要製作一個像這樣的輸出:

PNRFNAME | PNRFNAME | Salary_Difference 
---------+----------+------------------ 
Jason | Vicki |  483778.43 
Jason | Tiff  | -34540999.72 
Vicki | Tiff  | -35024778.15 

,我目前已經充滿了這個數據表:

PresenterID | PnrLName   | PnrFName | age | years | Salary_Yearly 
------------+------------------+----------+-----+-------+-------------- 
EMP_01  | NEEDELL   | Tiff  | 61 | 10 | 37451000.70 
EMP_02  | BUTLER-HENDERSON | Vicki | 41 | 10 | 2426222.55 
EMP_03  | PLATO   | Jason | 45 | 8 | 2910000.98 

的代碼,我到目前爲止有:

SELECT 
    a.Pnr_FName, b.Pnr_FName, 
    CONCAT((a.Salary_Yearly - b.Salary_Yearly), (a.Salary_Yearly - a.Salary_Yearly)) AS Salary_Difference 
FROM 
    PRESENTERS b 
CROSS JOIN 
    PRESENTERS a 

希望這是有道理的!我試圖讓我的問題明確

+0

如果您想要將值與前一行或後一行進行比較,則需要研究LEAD和LAG如果您有SQL 2012 – scsimon

+0

[SQL Server的可能重複:比較同一表中的人員薪水並顯示兩個名稱](http://stackoverflow.com/questions/39129803/sql-server-compare-salary-of-people-in-the-same-table-and-display-both-names) –

回答

0

試試這個:

CREATE TABLE #PRESENTERS(PRESENTERID VARCHAR(20), PNRLNAME VARCHAR(25), PNRFNAME VARCHAR(25), AGE INT, YEAR INT , SALARY_YEARLY NUMERIC(11,2)) 

INSERT INTO #PRESENTERS 

SELECT 'EMP_01','NEEDELL','TIFF',61,10,37451000.7   UNION ALL 
SELECT 'EMP_02','BUTLER-HENDERSON','VICKI',41,10,2426222.55 UNION ALL 
SELECT 'EMP_03','PLATO','JASON',45,8,2910000.98 

;WITH A 
AS 
(
SELECT ROW_NUMBER() OVER (ORDER BY PRESENTERID DESC) RN, * 
FROM #PRESENTERS 
) 
SELECT A.PNRFNAME , A2.PNRFNAME, A.SALARY_YEARLY - A2.SALARY_YEARLY SALARY_DIFF 
FROM A 
INNER JOIN A A2 ON A.RN < A2.RN 
0

您可以使用超前或滯後於得到這樣的:使用下面的查詢,

;with cte as (
select pnrfname, Salary_yearly, lag(salary_yearly) over (order by presenterid) lag_sal, 
lag(pnrfname) over (order by presenterid) as lag_fname from #PRESENTERS 
) select pnrfname, lag_fname, salary_yearly-lag_sal from cte 

這是解決你的要求嗎?