I have a table called findhighest_secondstep
with data like this:
id department top_employee highest_salary rownumber1
-----------------------------------------------------------
5 Finance Shane 6300 1
10 Finance Laura 6300 1
7 HR Vik 7200 1
3 IT Kate 7500 1
14 Marketing Elice 6800 1
6 Sales Shed 8000 1
I want to return a table with columns department, top_employee and highest_salary while I know in Finance department we have 2 people having the same salary. So I want to show all of them.
SELECT
hs.department AS department,
top_employee = STUFF((SELECT ', ' + top_employee
FROM findhighest_secondstep
FOR XML PATH('')), 1, 1, '')
FROM
findhighest_secondstep hs
GROUP BY
hs.department
This is what I got:
department top_employee
--------------------------------------------------
Finance Shane, Laura, Vik, Kate, Elice, Shed
HR Shane, Laura, Vik, Kate, Elice, Shed
IT Shane, Laura, Vik, Kate, Elice, Shed
Marketing Shane, Laura, Vik, Kate, Elice, Shed
Sales Shane, Laura, Vik, Kate, Elice, Shed
What I want:
department top_employee highest_salary
---------------------------------------------
Finance Shane, Laura 6300
HR Vik 7200
IT Kate 7500
Marketing Elice 6800
Sales Shed 8000
You need a correlated subquery:
SELECT hs.department AS department,
STUFF( (SELECT ', ' + top_employee
FROM findhighest_secondstep hs2
WHERE hs2.department = hs.department
FOR XML PATH('')
), 1, 2, ''
) as top_employees
FROM findhighest_secondstep hs
GROUP BY hs.department
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With