SQL Server有两个具有相同列的表但是选择没有null的数据

时间:2017-08-31 18:52:08

标签: sql sql-server

我有下面的示例数据,两个具有相同结构的临时表,但我需要获得一个表输出,在两个表之间取最佳值(这里的最佳值是NO NULL' s)。忽略两个表中两个相同列之间的空值。

表1

Prog    OrderNO ORDERKey    OrigType    REBNO   REBACC
A          1    1234        FACILITY    NULL    NULL
A          2    1234        FACILITY    NULL    NULL
A          3    1234        FACILITY    NULL    NULL

表2

Prog    OrderNO ORDERKey    OrigType    REBNO   REBACC
A          1    NULL            NULL    1234    456
A          2    NULL            NULL    1234    456
A          3    NULL            NULL    1234    456

输出

Prog    OrderNO ORDERKey    OrigType    REBNO   REBACC
A          1    1234        FACILITY    1234    456
A          2    1234        FACILITY    1234    456
A          3    1234        FACILITY    1234    456

1 个答案:

答案 0 :(得分:4)

使用COALESCE()结合FULL OUTER JOIN

SELECT
    COALESCE( Table1.Prog, Table2.Prog ) AS Prog,
    COALESCE( Table1.OrderNo, Table2.OrderNo ) AS OrderNo,

    COALESCE( Table1.OrderKey, Table2.OrderKey) AS OrderKey,
    COALESCE( Table1.OrigType, Table2.OrigType ) AS OrigType,
    COALESCE( Table1.RebNo, Table2.RebNo) AS RebNo,
    COALESCE( Table1.RebNo, Table2.RebNo) AS RebAcc
FROM
    Table1
    FULL OUTER JOIN Table2 ON
        Table1.Prog = Table2.Prog
        AND
        Table1.OrderNo = Table2.OrderNo