我想在oracle表中选择非不同的记录(仅选择重复的记录)

时间:2015-03-25 08:04:05

标签: sql oracle duplicates

以下是表(客户),记录如下:

CUSTID  CUSTNAME
100     ashwin
100     ashwin
200     adithyan
100     ashwin
300     aravind
300     aravind
300     aravind

我希望结果像这样(非不同的行):

CUSTID  CUSTNAME
100     ashwin
100     ashwin
300     aravind
300     aravind

2 个答案:

答案 0 :(得分:1)

  

我希望结果像这样(非不同的行):

CUSTID  CUSTNAME
100     ashwin
100     ashwin
300     aravind
300     aravind

如果我理解正确,您需要其余的重复行。您可以使用分析 ROW_NUMBER

测试案例

SQL> CREATE TABLE t
  2      (CUSTID int, CUSTNAME varchar2(8));

Table created.

SQL>
SQL> INSERT ALL
  2      INTO t (CUSTID, CUSTNAME)
  3           VALUES (100, 'ashwin')
  4      INTO t (CUSTID, CUSTNAME)
  5           VALUES (100, 'ashwin')
  6      INTO t (CUSTID, CUSTNAME)
  7           VALUES (200, 'adithyan')
  8      INTO t (CUSTID, CUSTNAME)
  9           VALUES (100, 'ashwin')
 10      INTO t (CUSTID, CUSTNAME)
 11           VALUES (300, 'aravind')
 12      INTO t (CUSTID, CUSTNAME)
 13           VALUES (300, 'aravind')
 14      INTO t (CUSTID, CUSTNAME)
 15           VALUES (300, 'aravind')
 16  SELECT * FROM dual;

7 rows created.

SQL>
SQL> COMMIT;

Commit complete.

SQL>

使用 ROW_NUMBER

进行查询
SQL> select custid, custname
  2  from (
  3    SELECT custid, custname,
  4           row_number() over (partition by custid order by custid) as rn
  5    from t
  6  )
  7  WHERE rn > 1
  8  order by custid;

    CUSTID CUSTNAME
---------- --------
       100 ashwin
       100 ashwin
       300 aravind
       300 aravind

SQL>

提供您想要的输出。

答案 1 :(得分:0)

试试这个:

select custid, custname
from customer a where
exists (
select CUSTID, CUSTNAME, count(*)
from customer b
where a.custid = b.custid and a.custname = b.custname
group by CUSTID, CUSTNAME
having count(*) > 1)