Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Concatenate Multiple Rows By Group Using FOR XML PATH

Tags:

sql

sql-server

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
like image 890
Bean Huang Avatar asked Mar 03 '23 09:03

Bean Huang


1 Answers

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
like image 78
Gordon Linoff Avatar answered Mar 06 '23 01:03

Gordon Linoff