2013-02-12 103 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