I'm trying to have the 'test' column in the same row. I'm using Stuff()
however, it seems that the 'test' column is going through all the qID
What am I missing?
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=qID
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl
WHERE qID in (2258060,2296222)
GROUP BY qID
You were missing alias on table
By using alias:
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=A.qID
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl A
WHERE qID in (2258060,2296222)
GROUP BY qID
Its also possible without alias on outer query, by using the table name itself.
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=tbl.qID --Table name before qid here
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl
WHERE qID in (2258060,2296222)
GROUP BY qID