I'm making a view and in one column I will have some names concatenated together.
Ideally in this one column I want the result to look something like the below:
ResultA, ResultB, ResultC and ResultD
ResultB, ResultC and ResultD
ResultA and ResultD
So I want it to keep putting commas between results until it reaches the last result where it places an AND in front of it instead of a comma.
I can do the query to grab what columns I need but can't figure out how to do the above...
select
isnull(replace(isnull(givenname, '') + ' ' +
(isnull(middlename, '') + ' ' + (isnull(lastname, ''), ' ', ' '), '') +
isnull(companyname, '') as Name
from
table1 with (nolock)
left outer join
table2 on t1key = t2key
left outer join
table3 ON t1key = t3key
I found this query somewhere else that will put everything with a comma for me, but I still need the 'and' for before the last result.
SELECT
ID, Name,
STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))
FROM @T T2
WHERE T1.id = T2.id AND T1.name = T2.name
FOR XML PATH('')), 1, 1, '') SOMECOLUMN
FROM
@T T1
GROUP BY
id, Name