I found this solution, working, but not necessarily the best one.
It is based on adding row_number column to your query and then selecting your 3 columns using COALESCE(MAX(
. (see SQL Server : Transpose rows to columns)
It seems to me better in this case than using t-sql PIVOT
.
SELECT
COALESCE(MAX(CASE WHEN x = 1 THEN [Employee Full Name] END), 'n/a') as FirstEmp,
COALESCE(MAX(CASE WHEN x = 2 THEN [Employee Full Name] END), 'n/a') as SecondEmp,
COALESCE(MAX(CASE WHEN x = 3 THEN [Employee Full Name] END), 'n/a') as ThirdEmp
FROM (
select top 3
row_number() over(order by [Annual Salary] desc) x,
[Employee First Name]+' '+[Employee Surname] as [Employee Full Name]
from Emp
group by [Employee First Name],[Employee Surname],[Annual Salary]
order by [Annual Salary] desc
) empRanks
I have replaced order by sum([Annual Salary]) desc
with order by [Annual Salary] desc
because the inner SELECT is grouped by [Annual Salary]
already.
Script I have used to populate data to test it:
DECLARE @emp TABLE
(
[Employee First Name] varchar(50) NULL,
[Employee Surname] varchar(50) NULL,
[Annual Salary] int NULL
)
INSERT INTO @emp VALUES ('Darren','Ben',500)
INSERT INTO @emp VALUES ('Sam','nixon',600)
INSERT INTO @emp VALUES ('Frances','Oliv',700)
INSERT INTO @emp VALUES ('AAFrances','AAAOliv',200)
INSERT INTO @emp VALUES ('AAFrancsasaes','AAAOsasaliv',2000)