Obed Tsagane Obed Tsagane - 3 months ago 10
SQL Question

Find the differrence between employees' salaries and sort by highest to lowest

I have a table like this:

NAME SALARY
Gareth 37451000.7
Lorah 2426222.55
Sage 2910000.98


I would like to find the difference between each employee's salary, sorted by highest to lowest difference? Like this...

NAME name salary diff
Sage Lorah 483778.43
Sage Gareth -34540999.72
Lorah Gareth -35024778.15


How do I go about coding this result? Thanks.

Answer
SELECT 
    a.Name
    ,b.Name
    ,a.salary - b.salary as 'Salary Difference'
FROM #salary a 
JOIN #salary b 
    ON a.name != b.name 
    AND b.id < a.id