SQL查询 - ID加入,只需重复

时间:2013-08-22 17:33:18

标签: sql oracle

我正在使用Oracle SQL。我有两张桌子。一个具有ItemID和DatePurchased,另一个具有ItemID,CustomerID。我正在尝试加入表格,以便只能看到有多个项目的客户。

换句话说,如果我有:

TABLE 1
ItemID---DatePurchased
   1         MAR15
   2         JUN10
   3         APR02

TABLE 2
ItemID---CustomerID
  1          1
  2          1
  3          2

我希望这返回:

TABLE 3
ItemID--DatePurchased--CustomerID
  1          MAR15         1
  2          JUN10         1

(客户2被遗漏,因为他只有一个项目(ItemID = 3))。

关于如何在SQL中执行此操作的任何想法?

2 个答案:

答案 0 :(得分:1)

select
    T2.ItemID, T2.CustomerID, T1.DatePurchased
from TABLE2 as T2
    inner join TABLE1 as T1 on T1.ItemID = T2.ItemID
where
    T2.CustomerID in
    ( 
        select TT.CustomerID
        from TABLE2 as TT
        group by TT.CustomerID
        having count(*) > 1
    )

答案 1 :(得分:1)

select ItemID, DatePurchased, CustomerID
from
 (
   select
      T1.ItemID, T1.DatePurchased, T2.CustomerID, 
      count(*) over (partition by T2.CustomerId) as ItemCnt
   from TABLE2 T2
      join TABLE1 T1 on T1.ItemID = T2.ItemID
 ) dt
 where ItemCnt > 1