如何用另一个表中的信息替换空数据?

时间:2015-01-20 18:59:20

标签: sql-server-2008

Order_ID       ship_state     bill_state
   121            null            CA
   122            WA              IN    
   123            CA              OR
   124            null            FL

我有一个查询(下面)带回这些结果(上图)。 Order_ID,Ship_state和bill_state分别位于不同的表中。如何修改我的查询,以便使用相应的bill_state填充null ship_state?某些订单会直接发送到帐单邮寄地址,这会使送货字段为空,因为它们会留空。我想生成一份船到州的清单。

SELECT  ca.STATE AS ship_state, 
        co.ID, 
        co.CUSTOMER_ID, 
        ca.ADDR_NO, 
        co.SHIP_TO_ADDR_NO, 
        c.STATE AS Bill_state, 
        c.NAME AS Bill_name, 
        ca.NAME AS Ship_name, 
        col.PART_ID, 
        col.ORDER_QTY, 
        ca.COUNTRY AS Ship_Country, 
        c.COUNTRY AS Bill_country, 
        co.ORDER_DATE
FROM dbo.CUST_ORDER_LINE AS col 
FULL OUTER JOIN dbo.CUST_ADDRESS AS ca 
    FULL OUTER JOIN dbo.CUSTOMER AS c 
        INNER JOIN dbo.CUSTOMER_ORDER AS co 
            ON c.ID = co.CUSTOMER_ID 
        ON ca.CUSTOMER_ID = co.CUSTOMER_ID 
        AND ca.ADDR_NO = co.SHIP_TO_ADDR_NO 
        AND ca.CUSTOMER_ID = c.ID 
    ON col.CUST_ORDER_ID = co.ID
WHERE co.ORDER_DATE > '2014-1-1'
  AND co.ID NOT LIKE 'rma%'
ORDER BY co.ID

2 个答案:

答案 0 :(得分:0)

使用ISNULL功能,

ISNULL(ca.State, c.State) As ship_state

答案 1 :(得分:0)

您可以使用COALESCE功能:

SELECT

COALESCE(ca.STATE, c.STATE) AS ship_state

如果c.STATEca.STATE,则会返回NULL的值。