1

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

enter image description here

0

1 Answer 1

5

You were missing alias on table

  1. Condition B.qID=qID returns always true as if 1=1, it was not doing anything. It was similar to B.qID=B.qID.

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
Sign up to request clarification or add additional context in comments.

3 Comments

@DaleK I tested the result using his and mine query.
Thanks. That did it. Do you know why without the alias it seems to retrieve everything?
@Camus In your query B.qID=qID returns always true as if 1=1, it was not doing anything. It was similar to B.qID=B.qID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.