I have an issue where I need to concatenate the values of a child table into one field, while also respecting an OR condition in the where clause. Let's say I'm working in the Northwind database, and I have a query such as:
SELECT c.CategoryName, p.ProductName FROM Products p join Categories c on p.CategoryID = c.CategoryID
where c.CategoryName like '%on%' or p.ProductName = 'Vegie-spread'
order by c.CategoryName, p.ProductName
I want all the product names to be concatenated into one field for each category name, so that the Products field would look like this:
Aniseed Syrup-Chef Anton's Cajun Seasoning-Chef Anton's Gumbo Mix-etc.
My first attempt looks like this:
select c.CategoryName, ISNULL(products.line, '') AS ProductNames
from Categories c
cross apply (
select CAST((select p.ProductName + '-'
from products p
where c.CategoryID = p.CategoryID
and (c.CategoryName like '%on%' or p.ProductName = 'Vegie-spread')
order by p.ProductName
for xml path('')) as nvarchar(max)) line
) products
order by c.CategoryName
But that returns some categories that don't match the where conditions. I want the results to be just as if I typed this query:
SELECT c.CategoryName, p.ProductName FROM Products p join Categories c on p.CategoryID = c.CategoryID
where c.CategoryName like '%on%' or p.ProductName = 'Vegie-spread'
order by c.CategoryName, p.ProductName
except that I want one line per category with all the products concatenated that match the query.
Can someone show me how to do this?