Home Oracle 查询表中重复数据
Post
Cancel

Oracle 查询表中重复数据

1、查找表中的重复记录,重复记录是根据单个字段(peopleId)来判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SELECT
  *
FROM
  people
WHERE
  peopleId IN (
    SELECT
      peopleId
    FROM
      people
    GROUP BY
      peopleId
    HAVING
      count(peopleId) > 1
  )

2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
DELETE FROM
  people
WHERE
  peopleId IN (
    SELECT
      peopleId
    FROM
      people
    GROUP BY
      peopleId
    HAVING
      count(peopleId) > 1
  )
  AND rowid NOT IN (
    SELECT
      min(rowid)
    FROM
      people
    GROUP BY
      peopleId
    HAVING
      count(peopleId) > 1
  )

3、查找表中多余的重复记录(多个字段) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
SELECT
  *
FROM
  vitae a
WHERE
  (a.peopleId, a.seq) IN (
    SELECT
      peopleId,
      seq
    FROM
      vitae
    GROUP BY
      peopleId,
      seq
    HAVING
      count(*) > 1
  )

4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
DELETE FROM
  vitae a
WHERE
  (a.peopleId, a.seq) IN (
    SELECT
      peopleId,
      seq
    FROM
      vitae
    GROUP BY
      peopleId,
      seq
    HAVING
      count(*) > 1
  )
  AND rowid NOT IN (
    SELECT
      min(rowid)
    FROM
      vitae
    GROUP BY
      peopleId,
      seq
    HAVING
      count(*) > 1
  )

比方说,在A表中存在一个字段“name”,而且不同记录之间的“name”值有可能会相同,现在就需要查询出在该表中的各记录之间,“name”值存在重复的项

1
2
3
4
5
6
7
8
9
SELECT
  NAME,
  Count(*)
FROM
  A
GROUP BY
  NAME
HAVING
  Count(*) > 1

如果还查性别也相同大则如下

1
2
3
4
5
6
7
8
9
10
11
SELECT
  NAME,
  sex,
  Count(*)
FROM
  A
GROUP BY
  NAME,
  sex
HAVING
  Count(*) > 1
This post is licensed under CC BY 4.0 by the author.