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;

如何找到一对多的情况,即选择那些名称有多个 acc_num 的?

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

3 回答 3

4

在这种情况下,您需要使用GROUP BY和。HAVING

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
于 2012-12-26T12:26:17.813 回答
1

This query seems designed for the analytic functions:

select name, acc_num
from (select om.*,
             count(*) over (partition by name) as NumOnAccount
      from one_many om
     ) t
where NumOnAccount > 1
于 2012-12-26T16:36:21.140 回答
0

你可以这样做

      SELECT * FROM one_many
       WHERE acc_num IN 
                     (SELECT acc_num FROM 
                                     one_many
                                      GROUP BY name ,acc_num 
                                       HAVING COUNT(*)>1
                      );
于 2012-12-26T12:32:30.560 回答