0

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

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

2 回答 2

4

要获得Customer_id多个不同的Prospect_id

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

请参阅带有演示的 SQL Fiddle

如果您想返回所有详细信息,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

于 2013-02-12T20:17:21.977 回答
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
于 2013-02-12T20:26:54.693 回答