2016-09-20 30 views
0

我擁有與另一個表(table2 - 包含客戶聯繫信息)相關的主表(table1 - 包含客戶主要信息),常用值爲ID通過SQL查詢找到複雜條件下的空值

在主表中的ID值給我1列,另一個表可以給我更多的行,這取決於有多少接觸類型的客戶有,例如:

  • main_phone(該行始終存在)
  • HOME_PHONE
  • work_phone
  • 移動等

我試圖實現:

首先我想檢查移動值,如果行丟失或沒有移動值,但行存在,那麼我想檢查main_phone值。

但是,如果有mobile值,那麼我不想檢查main_phone值。 如果main_phone值也丟失,那麼我想要這些記錄。

目前,我有查詢:

Select customer 
From table1 t1 
Join table2 t2 on t1.id = t2.id 
Where t2.type in (main_phone, mobile) 
    And t2.type_values in ('',null,'-') 

但問題是,如果客戶有手機號碼和失蹤的電話號碼,這些客戶記錄也是在結果中顯示。

+0

顯示正確的數據樣本和預期的結果 – scaisEdge

+0

這裏是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

+0

您是否在尋找沒有手機或main_phone號碼的客戶? – Beth

回答

0

這可能讓你關閉..

SELECT customer 
FROM table1 t1 
WHERE NOT EXISTS (
    SELECT 1 
    FROM table2 t2 
    WHERE t1.id = t2.id 
      AND t2.type in (main_phone, mobile) 
      and ISNULL(t2.type_value,'') NOT IN ('','-') 
) 

如果發現價值在NOT EXISTS查詢將被排除

0

你必須要小心,並把null作爲一個特殊的價值。下面的兩個查詢將返回不同的結果。

Select COUNT(*) from table1 t1 
join table2 t2 on t1.id=t2.id 
where t2.type in (main_phone, mobile) 
and t2.type_values in ('',null,'-') 

Select COUNT(*) from table1 t1 
join table2 t2 on t1.id=t2.id 
where t2.type in (main_phone, mobile) 
and (t2.type_values IS NULL) OR(t2.type_values in ('','-')) 

你應該在測試使用空比較,如X空的習慣是NULL,不是X IS NULL,ISNULL()或者COALESCE()。

0

你想要這樣的東西嗎?

SELECT 
    customer 
FROM 
    table1 t1 JOIN 
    (SELECT 
     id 
    FROM 
     table1 t1 JOIN 
     table2 t2 ON 
     t1.id=t2.id 
    WHERE 
     t2.TYPE = mobile AND 
     (t2.type_values IS NULL OR 
     t2.type_values IN ('','-'))) missing_mobile ON 
    t1.id = missing_mobile.id 
WHERE 
     t2.TYPE = main_phone AND 
     (t2.type_values IS NULL OR 
     t2.type_values IN ('','-'))