I am using SQL Server 2012 (v11.0.5058.0 - X64). I want to perform comma separated for multiple columns. Since my SQL Server version is 2012 I can't use string_agg
or ListAgg
so I am trying with a CTE and FOR XML PATH
which is new for me.
Output Explanation:
Supposed If One staff ID
Contain multiple Cost_Center
then it should comma separated for respective Staff_ID
Current table:
Staff_No | Name | CostCenter | status |
---------+--------+----------------+----------+
1270 | WASI | 850110 - CPP | Active |
1345 | FAK | 124600 - CPP | Active |
1270 | WASI | 850870 - BKR | Active |
Desired output:
Staff_No | Name | CostCenter | status |
---------+--------+------------------------------+----------+
1270 | WASI | 850110 - CPP , 850870 - BKR | Active |
1345 | FAK | 124600 - CPP | Active |
I tried this code:
WITH CTE_TableName AS
(
SELECT
a.Staff_No, a.Name,
CONVERT(varchar(19), a.COST_CENTER_CODE) + ' - ' + b.COST_CENTER_DESC as CostCenter,
CASE a.Active
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
END AS status
FROM
[FAV_VS_STAFF_M] a, [FAV_VS_COST_CENTER_M] b
)
SELECT
t0.Staff_No, t0.Name, t0.status,
STUFF((SELECT ',' + t2.CostCenter
FROM CTE_TableName t2
WHERE t2.Staff_No = t0.Staff_No
ORDER BY t2.CostCenter
FOR XML PATH('')), 1, LEN(','), '') AS FieldBs
FROM
CTE_TableName t0
GROUP BY
t0.Staff_No , t0.Name, t0.status
ORDER BY
Staff_No;
I am not getting the desired output. Where I am going wrong? Please help me