删除Table Join with Case Statement中的重复项

时间:2011-09-22 18:58:43

标签: sql sql-server sql-server-2005 tsql

无论电话是来自工作还是家庭,我都需要能够选择不同的“电话”。所有手机都必须是独一无二的。

当在工作中找到相同的手机并且在不同的行中找到家中时,此查询会产生重复。

SELECT CASE WorkPhone
        WHEN '' THEN 
            HomePhone
        ELSE 
            WorkPhone
        END AS Phone
       ,MAX(LastName)
       ,MAX(FirstName)
FROM   TableA
WHERE  (statusid = Inactive)
        AND 
            (modifieddate > '11/11/2011')       
        AND 
            NOT EXISTS (SELECT Phone FROM TableB WHERE Phone = WorkPhone OR Phone = HomePhone)      
        AND 
            NOT EXISTS (
            SELECT AreaCode + PhoneNumber FROM TableC 
            WHERE   
                (AreaCode = LEFT(WorkPhone,3) AND PhoneNumber = Substring(WorkPhone, 4, 7)
                )
                OR
                (AreaCode = LEFT(HomePhone,3) AND PhoneNumber = Substring(HomePhone, 4, 7))                             
                )

GROUP BY WorkPhone, HomePhone

1 个答案:

答案 0 :(得分:2)

你应该分组:

CASE WorkPhone
        WHEN '' THEN 
            HomePhone
        ELSE 
            WorkPhone
        END

而不是按WorkPhone, HomePhone分组