Oracle重复数据删除

时间:2018-07-26 16:56:41

标签: sql oracle duplicates

我有以下数据:

ID    ID2      DATE
 A     AA    2017-01-01
 A     BB    2017-01-01
 A     CC    2017-01-01
 B     DD    2018-01-01
 B     DD    2018-01-01
 C     EE    2018-02-01

我想通过ID重复数据删除,每行仅保留一个ID2和一个日期。我正在尝试此sql命令,但它不会重复数据删除:

SELECT DISTINCT A.ID, A.ID2, A.DATE  
FROM TABLE A
GROUP BY A.ID; 

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

似乎您不在乎ID2DATUM(因为您不能将列“ DATE”命名;它是为数据类型保留的),因此, d要保留,一个简单的选择是

SQL> with test (id, id2, datum) as
  2    (select 'a', 'aa', date '2017-01-01' from dual union all
  3     select 'a', 'bb', date '2017-01-01' from dual union all
  4     select 'a', 'cc', date '2017-01-01' from dual union all
  5     select 'b', 'dd', date '2018-01-01' from dual union all
  6     select 'b', 'dd', date '2018-01-01' from dual union all
  7     select 'c', 'ee', date '2018-02-01' from dual
  8    )
  9  select id, min(id2) id2, min(datum) datum
 10  from test
 11  group by id;

ID  ID2 DATUM
--- --- ----------
a   aa  2017-01-01
b   dd  2018-01-01
c   ee  2018-02-01

SQL>

答案 1 :(得分:0)

您可以使用RPT

row_number()

如果有特定日期(例如最小日期或最大日期),则可以更改select id, id2, date from (select t.*, row_number() over (partition by id order by id) as seqnum from t ) t where seqnum = 1;