2012-12-26 52 views
0
CREATE TABLE one_many 
    (name VARCHAR2(20), 
    acc_num VARCHAR2(20)) 

    INSERT ALL 
    INTO one_many VALUES ('abc','a-110') 
    INTO one_many VALUES ('def','b-256') 
    INTO one_many VALUES ('xyz','v-586') 
    INTO one_many VALUES ('uij','o-451') 
    INTO one_many VALUES ('pqr','') 
    INTO one_many VALUES ('abc','a-120') 
    INTO one_many VALUES ('xyz','v-588') 
    SELECT * FROM dual; 

如何找到一個很多的情況,即SELECT這些名字有多個acc_num?找到名稱HAVING多個帳號

Desired o/p: 
NAME ACC_NUM 
abc a-110 
abc a-120 
xyz v-586 
xyz v-588 

回答

4

在這種情況下,您需要使用GROUP BYHAVING

SELECT name, COUNT(*) totalCount 
FROM one_many 
GROUP BY name 
HAVING COUNT(*) > 1 

也許這就是你的意思。

SELECT a.* 
FROM one_many a 
    INNER JOIN 
     (
     SELECT name, COUNT(*) totalCount 
     FROM one_many 
     GROUP BY name 
     HAVING COUNT(*) > 1 
    ) b ON a.name = b.name 
+0

感謝也需要t o顯示多個acc_name。 – sam

+0

你是什麼意思多個帳戶名稱? –

+0

@sam在上面看到我的更新。 –

0

u能做到這樣

 SELECT * FROM one_many 
     WHERE acc_num IN 
        (SELECT acc_num FROM 
            one_many 
             GROUP BY name ,acc_num 
             HAVING COUNT(*)>1 
        ); 
1

該查詢似乎專爲分析功能:快速回復,但我

select name, acc_num 
from (select om.*, 
      count(*) over (partition by name) as NumOnAccount 
     from one_many om 
    ) t 
where NumOnAccount > 1