我有一个名为 findhighest_secondstep
的表,其中包含如下数据:
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
我想返回一个包含部门、top_employee 和最高工资列的表,而我知道在财务部门我们有 2 个人的工资相同。所以我想展示所有这些。
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
这就是我得到的:
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
我想要什么:
department top_employee highest_salary
---------------------------------------------
Finance Shane, Laura 6300
HR Vik 7200
IT Kate 7500
Marketing Elice 6800
Sales Shed 8000
最佳答案
您需要一个相关子查询:
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
关于SQL Server 使用 FOR XML PATH 按组连接多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065835/