SQL查询逻辑多个记录

时间:2013-02-12 20:06:59

标签: sql

我需要创建一个查询来返回Customer_ID与其关联的多个Prospect_ID的行。例如,我希望查询返回下面的第2行和第3行,因为Customer_ID是相同的,但Prospect_ID是不同的,但不是第5行和第6行,因为Prospect_ids是相同的:

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

2 个答案:

答案 0 :(得分:4)

要获得具有多个不同Customer_id的{​​{1}}:

Prospect_id

请参阅SQL Fiddle with Demo

如果您想要返回select customer_id from yourtable group by customer_id having count(distinct prospect_id) >1 的所有详细信息,那么您可以使用:

Customer_Ids

请参阅SQL Fiddle with Demo

这也可以写成(感谢@ypercube):

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

答案 1 :(得分: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