当存在重复项时加入特定条件 - SQL

时间:2017-05-01 19:17:44

标签: sql sql-server

在下面的示例中,我正在尝试加入account_number上的另一个表。问题是该表中有一些重复的帐号,我想根据字段是否为NULL来指定它应该加入哪个帐号。

以下是我的例子:

SELECT
 a.Account_Number
,b.Property_Address

FROM
Table1 a

left join Table2 b
on a.account_number = b.account_number

WHERE
b.property_address is not null

表二目前看起来像这样:

帐号123456

帐号123456

Property_Address NULL

Property_Address 123 Fake Street

_

我希望我的查询能够解决这个问题:

帐号123456

Property_Address 123 Fake Street

_

目前正在拉动这个:

帐号123456

Property_Address NULL

谢谢。

3 个答案:

答案 0 :(得分:0)

我会将您的左连接更改为内连接,您可能会获得所需的结果:

SELECT a.Account_Number ,b.Property_Address

FROM Table1 a

inner join Table2 b on a.account_number = b.account_number

WHERE b.property_address is not null

答案 1 :(得分:0)

您使用左连接,但您的where子句引用了未保留的表(表2)。这会将您的左连接转换为内连接。我猜这可能不是你想要的。而是希望包含Table2中那些列不为null的行。因此,将条件从where子句移动到连接中。例如,

left join Table2 as b on a.account_number = b.account_number 
and b.property_address is not null

答案 2 :(得分:0)

为什么不是这样的?

WITH CTE AS (
    SELECT account_number, property_address
    FROM Table2 
    WHERE property_address IS NOT NULL )

SELECT 
     a.Account_Number
    ,b.Property_Address
FROM CTE b 
INNER JOIN Table1 a ON b.Account_Number = a.Account_Number