3

我有两张表 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

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

谢谢。

4

5 回答 5

3

我终于想通了...

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

谢谢你让我走上正轨。

于 2010-06-09T12:40:03.320 回答
1

试一试

SELECT *
FROM CustomerAddress ca
INNER JOIN CustomerTransactions ct
    ON ca.CustomerId = ct.CustomerId
GROUP BY ct.CustomerId, ct.CustomerContact
于 2010-06-09T00:00:37.183 回答
0

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

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

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

于 2010-06-09T00:05:16.957 回答
0

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

于 2010-06-08T23:38:47.050 回答
0
select distinct 
   ca.CustomerAddressID
  ,ca.City
  ,ca.Country
  ,ct.CustomerContact
from CustomerAddress ca
left join CustomerTransaction ct on ca.CustomerID = ct.CustomerID

与 distinct 你不会得到卡门两次

于 2010-06-09T09:07:19.563 回答