Well, it's not an exact duplicate of the question Lad2025 linked to,
but the answers to that question does show how to convert values of different rows into a comma separated string.
The one thing you have left to do is to get a distinct list of emails per vat from both columns.
Here is one way to do it:
First, Create and populate sample table (Please save us this step in your future questions):
DECLARE @T AS TABLE
(
VAT char(3),
Email1 char(6),
Email2 char(6)
)
INSERT INTO @T(VAT,Email1, Email2) VALUES
('000', 'a@a.it', 'b@b.it'),
('000', 'a@a.it', NULL),
('000', 'a@a.it', 'c@c.it'),
('000', NULL, 'd@d.it')
Then, use a common table expression to combine values from email1
and email2
using union
.
Note that union
will remove duplicate values so you will get a distinct list of emails for each vat value:
;WITH CTE AS
(
SELECT VAT, Email1 As Email
FROM @T
UNION
SELECT VAT, Email2
FROM @T
)
Then use for xml path
to get a comma delimited list from the email column of the cte (that will ignore the null
values), and stuff
to remove the first comma:
SELECT DISTINCT VAT,
(
SELECT STUFF(
(SELECT ',' + Email
FROM CTE t1
WHERE t0.VAT = t1.VAT
FOR XML PATH(''))
, 1, 1, '')
) As Emails
FROM CTE t0
Results:
VAT Emails
000 a@a.it,b@b.it,c@c.it,d@d.it