如何在t-sql

时间:2017-04-28 15:00:10

标签: sql sql-server tsql

我有一个表,包含两列:

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

对于每个Column1,我想得到一个以分号分隔的Column2值列表,所以这是我的代码:

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

当然,当t1.Column1为null时,内部查询不会返回任何内容,因为null不等于null。但是,当Column1为null时,我需要获取Column2的这些值,并将其显示在' Empty'字。知道如何做到这一点吗?

提前致谢。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

在where子句中添加另一个条件:

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 :(得分:0)

Try this 首先设置空值,以便您可以配对它们。