'How to concatenate values from a column grouping by a specific values from another column using TSQL?

I would like to concatenate the follow columns X, Y and Z, grouping by ProductToday and separating the values with comma " , " from my TSQL table.

enter image description here

As a result I would like to have it: enter image description here

Which query should I use to to it ?

P.S: some values from columns X,Y,Z are also Null.



Solution 1:[1]

You can use STRING_AGG() in sql server and GROUP_CONCAT in MySQL

For SQL Server:

SELECT 
    STRING_AGG(Z,',')
FROM 
    yourTable
GROUP BY ProductToday

For MySQL:

SELECT GROUP_CONCAT(Z SEPARATOR ',') FROM yourTable GROUP BY ProductToday;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bilal Bin Zia