2016-08-24 42 views
0

我有如下表:SQL服務器:在同一個表比較的人的工資,並顯示兩個名字,區別

For Presenters

,並希望得到的輸出如下:

Example

我試圖做一個內部聯接,但覺得有一點困惑,因爲我還是比較新的使用SQL

時I g OT從同一個表顯示2名,但不確定該將他們的工資比較,

這裏是我的代碼,我嘗試:

select 
    t1.PNRFNAME, t2.PNRFNAME, t1.SALARY_YEARLY 
from 
    PRESENTERS t1 
inner join 
    PRESENTERS t2 on t1.PRESENTER_ID = t2.PRESENTER_ID 
order by 
    t1.SALARY_YEARLY DESC 

回答

0

只需添加一個名爲Salary_Diff柱:

select t1.PNRFNAME,t2.PNRFNAME, t1.SALARY_YEARLY, 

t1.SALARY_YEARLY - t2.SALARY_YEARLY AS Salary_Diff 

from PRESENTERS t1 
cross join PRESENTERS t2 
where t1.presenterid <> t2.presenterid 
ORDER BY t1.SALARY_YEARLY DESC 
+0

感謝幫助了很多,我現在知道怎麼弄的差異,得到它的任何想法比較RO 2 ws與對方?因爲目前它會將同一行與自己進行比較,所以salary_diff仍等於0 – AdrianBeukes

+0

剛剛找到解決方案,在比較行時加上!=,感謝您的幫助 – AdrianBeukes

+1

@AdrianBeukes我剛剛更新瞭解決方案,我用交叉連接而不是連接。希望這一次它會起作用。 –

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