1

I have a table, containing two columns:

Column1  Column2
a        g
b        null
a        e
null     g
d        null
...      ...

For every Column1 I want to get a semicolon separated list of Column2 values, so here is my code:

select
    coalesce(t1.Column1, 'Empty') as col1,
    (
        select
            t2.Column2 + '; '
        from
            table as t2
        where
            t2.Column1 = t1.Column1
        for xml path(N'')
    ) as col2list
from
    table as t1

Of course, when the t1.Column1 is null, the inner query doesn't return anything, cause null is not equal to null. But I need to get these values of Column2 for cases when Column1 is null and display them against the 'Empty' word. Any idea how it could be done?

Thanks in advance.

3 Answers 3

2

try

select
    coalesce(t1.Column1, 'Empty') as col1,
    (
        select
            isnull(t2.Column2,'') + '; '
        from
            table as t2
        where
            isnull(t2.Column1,'') = isnull(t1.Column1,'')
        for xml path(N'')
    ) as col2list
from
    table as t1
Sign up to request clarification or add additional context in comments.

2 Comments

This will work only if an empty string is not considered a valid value for Column1. otherwise column1 empty strings will get the wrong list.
Zohar is correct, but that is still the answer for me. The only thing I need to mention is that datatype also matter. As soon as column1 is a guid a have to use hardcoded guid for compairing, like: isnull(t2.Column1, @EmptyGuid) = isnull(t1.Column1,@EmptyGuid)
1

Add another condition to your where clause:

select
    coalesce(t1.Column1, 'Empty') as col1,
    (
        select
            t2.Column2 + '; '
        from
            table as t2
        where
            t2.Column1 = t1.Column1
        or 
            (t2.Column1 is null and t1.Column1 is null)
        for xml path(N'')
    ) as col2list
from
    table as t1

2 Comments

This will not work because it would return null column2 values for all column1 values and not for these which has null in fact.
Actually, for the sample data you provided it works - rextester.com/UFGD60661
0

Try this sets null values first so that you can pair them up.

1 Comment

Yes. ISNULL (or COALESCE for T-SQL) is the answer, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.