不包括sql join中的空值

时间:2010-06-08 23:37:25

标签: sql sql-server tsql distinct-values

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

对于CustomerAddress:

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

对于CustomerTransactions:

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

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

感谢。

5 个答案:

答案 0 :(得分:2)

我终于明白了......

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

感谢您让我走上正轨。

答案 1 :(得分:1)

放手一搏

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

答案 2 :(得分:0)

只需添加WHERE子句即可确保该列不为空。

答案 3 :(得分:0)

这看起来像是我的左联盟。

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

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

答案 4 :(得分:0)

select distinct 
   ca.CustomerAddressID
  ,ca.City
  ,ca.Country
  ,ct.CustomerContact
from CustomerAddress ca
left join CustomerTransaction ct on ca.CustomerID = ct.CustomerID

与众不同,你不会得到两次卡门