2013-02-12 100 views
0

我需要創建一個查詢來返回Customer_ID具有多個與其關聯的Prospect_ID的行。例如,我希望查詢爲ale以返回下面的第2行和第3行,因爲Customer_ID相同,但Prospect_ID不同,但不是第5行和第6行,因爲Prospect_ids是相同的:SQL查詢邏輯多條記錄

Prospect_ID Customer_ID 
1001   31001 
1002   31002 
1003   31002 
1004   31003 
1005   31004 
1005   31004 
+0

歡迎SO!你能告訴我們到目前爲止你有什麼SQL嗎?你卡在哪裏? – Jacco 2013-02-12 20:18:26

+1

你使用的是什麼rdbms? – Taryn 2013-02-12 20:29:31

回答

4

要使用多個不同的Prospect_id得到Customer_id

select customer_id 
from yourtable 
group by customer_id 
having count(distinct prospect_id) >1 

SQL Fiddle with Demo

如果你想返回所有的這些Customer_Ids的細節,那麼你可以使用:

select * 
from yourtable t1 
where exists (select customer_id 
       from yourtable t2 
       where t1.customer_id = t2.customer_id 
       group by customer_id 
       having count(distinct prospect_id) >1) 

請參閱SQL Fiddle with Demo

這也可以寫成(感謝@ypercube):

select * 
from yourtable t1 
where exists (select customer_id 
       from yourtable t2 
       where t1.customer_id = t2.customer_id 
       and t1.prospect_id <> t2.prospect_id) 

SQL Fiddle with Demo

0

爲此,您可以用窗口的功能:

select prospect_id, customer_id 
from (select t.*, 
      COUNT(*) over (partition by prospect_id, customer_id) as cnt_pc, 
      COUNT(*) over (partition by customer_id) as cnt_c 
     from t 
    ) t 
where cnt_pc <> cnt_c and cnt_c > 1