2010-06-08 119 views
3

我有两个表CustomerAddress(CustomerId,City,Country)和CustomerTransactions(TransactionId,CustomerId,CustomerContact)。下面是表中的值:不包含sql中的空值加入

对于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 

这看起来像一个简单的加入,但我很难提出上述结果设置。请帮忙。

谢谢。

+0

您需要从此加入中获取哪些数据,特别是客户地址中的一行可能与客户交易中的多行有关 – 2010-06-08 23:43:57

+0

是的,customeraddress表中的一行可能与客户交易表中的多行有关。我需要CustomerContact列的不同值。 – Ashanti 2010-06-08 23:47:13

+0

无空值 – Ashanti 2010-06-08 23:49:53

回答

0

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

+1

这样做会消除所需结果集的第二行... – Ashanti 2010-06-08 23:44:51

0

给这个一去

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

这看起来像一个左联接给我。

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

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

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

具有鲜明的你不会得到卡门两次

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 

谢谢你把我在正确的轨道上。