My question really similar to this Use STUFF with INNER JOIN Query, but I've been trying what if the first column is a varchar
type, currently this is my table. As for note I'm using SQL Server 2014
Table Customer
Cust_ID | Cust_Name
--------+---------
1 | Name1
2 | Name2
Table Order
Order_ID | Order_NO | Cust_ID
---------+----------+---------
1 | No.001 | 1
2 | No.002 | 2
Table Item
Item_ID | Order_ID | Item_Name | Quantity | Price
--------+----------+-----------+----------+-------
1 | 1 | A | 1 | 10
2 | 1 | B | 1 | 20
3 | 1 | C | 1 | 30
4 | 2 | D | 1 | 40
A few queries that I've tried:
SELECT
TBL_Sales_SO.SO_NO AS int, Tbl_Customer.Customer_Name,
ITEMS = STUFF ((SELECT DISTINCT ',' + TBL_SO_LIITEM.Item_Name
FROM Tbl_Customer
INNER JOIN TBL_Sales_SO ON Tbl_Customer.Com_Customer_ID = TBL_Sales_SO.Com_Customer_ID
INNER JOIN TBL_SO_LIITEM ON TBL_Sales_SO.Sales_SO_ID = TBL_SO_LIITEM.Sales_So_ID
WHERE TBL_Sales_SO.SO_NO = TBL_Sales_SO.Sales_SO_ID
FOR XML PATH('')), 1, 1,'')
FROM
TBL_Sales_SO, Tbl_Customer
ORDER BY
SO_NO
and the query that for me I think almost hit
SELECT
TBL_Sales_SO.SO_NO, Tbl_Customer.Customer_Name, TBL_SO_LIITEM.Item_Name,
TBL_SO_LIITEM.Quantity, TBL_SO_LIITEM.Price
FROM
((Tbl_Customer
INNER JOIN
TBL_Sales_SO on Tbl_Customer.Com_Customer_ID = TBL_Sales_SO.Com_Customer_ID)
INNER JOIN
TBL_SO_LIITEM on TBL_Sales_SO.Com_Customer_ID = TBL_SO_LIITEM.Sales_So_ID)
While tinkering the first code give me some various error, the second one im just not sure how make possible something like my target
Order_No | Name | Item_Name | Quantity | Price
no.001 | Name1 | A,B,C | 3 | 60
no.002 | Name2 | D | 1 | 40
UPDATE Following Gordon Answer, i tinkering the code again, manage to the following table
Order_No| Name | Item_Name
no.001 | Name1 | A,B,C
no.001 | Name2 | D
no.002 | Name2 | D
no.002 | Name1 | A,B,C
and the query I use:
SELECT
s.SO_NO AS int, c.Cust_Name,
ITEMS = STUFF((SELECT DISTINCT ','+ Item_Name
FROM TBL_SO_LIITEM item
INNER JOIN TBL_Sales_SO s ON s.Sales_SO_ID = item.Sales_So_ID
WHERE c.Cust_ID = s.Cust_ID
FOR XML PATH('')), 1, 1, '')
FROM
TBL_Sales_SO s, Tbl_Customer c
WHERE
c.Cust_Name IN ('Name1','Name2')
ORDER BY
SO_NO