簡體   English   中英

SQL 服務器使用 FOR XML 路徑按組連接多行

[英]SQL Server Concatenate Multiple Rows By Group Using FOR XML PATH

我有一個名為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

您可以使用STRING_AGG 像這樣的東西:

SELECT department
      ,top_employee    
      ,STRING_AGG(highest_salary, ',')
FROM findhighest_secondstep 
GROUP BY department
        ,highest_salary

我們可以在這里嘗試使用STRING_AGG ,因為您使用的是 SQL Server 2017:

WITH cte AS (
    SELECT *, RANK() OVER (PARTITION BY department ORDER BY highest_salary DESC) rnk
    FROM findhighest_secondstep
)

SELECT
    department,
    STRING_AGG(top_employee, ',') AS top_employee,
    MAX(highest_salary) AS highest_salaray
FROM cte
WHERE
    rnk = 1
GROUP BY
    department;

這里的邏輯是,我們為給定部門中薪水最高的每個員工分配 1 級。 然后,我們按部門匯總,得出並列第一名的所有員工的 CSV 列表,以及最高薪水。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM