products
-----------------------------
| ProductId | ModelId |
|---------------------------|
| 12345 | A3666 |
| 12345 | A3667 |
| 12345 | A8999 |
| 12346 | A3666 |
| 12346 | A3667 |
-----------------------------
models
-----------------------------
| ModelId | Name |
|---------------------------|
| A3666 | win |
| A3667 | xia |
| A8999 | vor |
-----------------------------
I'm trying to get the output this way:
-----------------------------------
| ProductId | Models |
|---------------------------------|
| 12345 | win,xia,vor |
| 12346 | win,xia |
-----------------------------------
My code is :
SELECT
p.ProductId,
STUFF
(
(
SELECT ',' + Name
FROM models m
WHERE m.ModelId=p.ModelId
ORDER BY Name
FOR XML PATH(''), type
).value('.', 'varchar(max)'), 1, 1, ''
) AS ModelNames
FROM
products p
which gives the o/p :
-----------------------------
| ProductId | ModelNames |
|---------------------------|
| 12345 | win |
| 12345 | xia |
| 12345 | vor |
| 12346 | win |
| 12346 | xia |
-----------------------------
where am i going wrong. [I think the question was clear enough to be understood but SO wouldnt submit as it says, add more details, mostly code. hence this text.]