【问题标题】:not including null values in sql join在 sql join 中不包括空值
【发布时间】:2010-06-09 20:41:54
【问题描述】:

我有两个表 CustomerAddress(CustomerId, City, Country) 和 CustomerTransactions(TransactionId, CustomerId, CustomerContact)。以下是表中的值:

对于客户地址:

1001, El Paso, USA    
1002, Paris, France    
1003, Essen, Germany    

对于客户交易:

98, 1001, Phillip    
99, 1001, NULL
100, 1001, NULL    
101, 1003, Carmen    
102, 1003, Carmen    
103, 1003, Lola    
104, 1003, NULL    
105, 1002, NULL

我正在尝试加入两个表并获得以下结果集:

1001, El Paso, USA, Phillip    
1002, Paris, France, (empty string)    
1003, Essen, Germany, Carmen    
1003, Essen, Germany, Lola

这似乎是一个简单的联接,但我无法提出上述结果集。请帮忙。

谢谢。

【问题讨论】:

  • 你需要从这个join中得到什么数据,特别是客户地址中的一行可以与客户交易中的多行相关
  • 是的,customeraddress 表中的一行可以与customer transaction 表中的多行相关。我需要 CustomerContact 列的不同值。

标签: sql sql-server tsql distinct-values


【解决方案1】:

我终于明白了……

SELECT DISTINCT CA.CustomerId, CA.CustomerCity, CA.CustomerCountry, ISNULL(CT.CustomerContact) AS CustomerContact
FROM CustomerAddress CA
LEFT JOIN (SELECT CustomerId, CustomerContact 
           FROM CustomerTransactions
           WHERE CustomerContact IS NOT NULL) CT ON CT.CustomerID = CA.CustomerID

感谢您让我走上正轨。

【讨论】:

    【解决方案2】:

    试一试

    SELECT *
    FROM CustomerAddress ca
    INNER JOIN CustomerTransactions ct
        ON ca.CustomerId = ct.CustomerId
    GROUP BY ct.CustomerId, ct.CustomerContact
    

    【讨论】:

      【解决方案3】:

      只需添加一个WHERE 子句以确保该列不为空。

      【讨论】:

        【解决方案4】:

        对我来说,这看起来像是左连接。

        select ca.CustomerAddressID, ca.City, ca.Country, ISNULL(ct.CustomerContact, '')
        from CustomerAddress ca
        left join CustomerTransaction ct on ca.CustomerID = ct.CustomerID
        

        这样你就得到了所有的地址记录,如果没有对应的 CustomerTransaction 你应该得到一个空字符串。

        【讨论】:

          【解决方案5】:
          select distinct 
             ca.CustomerAddressID
            ,ca.City
            ,ca.Country
            ,ct.CustomerContact
          from CustomerAddress ca
          left join CustomerTransaction ct on ca.CustomerID = ct.CustomerID
          

          distinct 你不会得到 carmen 两次

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-11-30
            • 2015-08-03
            • 2012-12-29
            • 1970-01-01
            • 2016-01-12
            • 1970-01-01
            • 2017-06-03
            相关资源
            最近更新 更多