Count duplicates records in Mysql table?

2019-01-17 15:28发布

I have table with, folowing structure.

tbl

id   name  
1    AAA
2    BBB
3    BBB
4    BBB
5    AAA
6    CCC

select count(name) c from tbl
group by name having c >1

The query returning this result:

AAA(2)  duplicate
BBB(3)  duplicate
CCC(1)  not duplicate

The names who are duplicates as AAA and BBB. The final result, who I want is count of this duplicate records.

Result should be like this: Total duplicate products (2)

6条回答
Fickle 薄情
2楼-- · 2019-01-17 16:02

SQL code is:

SELECT VERSION_ID, PROJECT_ID, VERSION_NO, COUNT(VERSION_NO) AS dup_cnt
FROM MOVEMENTS
GROUP BY VERSION_NO
HAVING (dup_cnt > 1 && PROJECT_ID = 11660)
查看更多
姐就是有狂的资本
3楼-- · 2019-01-17 16:05

The accepted answer counts the number of rows that have duplicates, not the amount of duplicates. If you want to count the actual number of duplicates, use this:

SELECT COALESCE(SUM(rows) - count(1), 0) as dupes FROM(

    SELECT COUNT(1) as rows
    FROM `yourtable`
    GROUP BY `name`
    HAVING rows > 1

) x

What this does is total the duplicates in the group by, but then subtracts the amount of records that have duplicates. The reason is the group by total is not all duplicates, one record of each of those groupings is the unique row.

Fiddle: http://sqlfiddle.com/#!2/29639a/3

查看更多
相关推荐>>
4楼-- · 2019-01-17 16:13

why not just wrap this in a sub-query:

SELECT Count(*) TotalDups
FROM
(
    select Name, Count(*)
    from yourTable
    group by name
    having Count(*) > 1
) x

See SQL Fiddle with Demo

查看更多
Lonely孤独者°
5楼-- · 2019-01-17 16:13

Use IF statement to get your desired output:

SELECT name, COUNT(*) AS times, IF (COUNT(*)>1,"duplicated", "not duplicated") AS duplicated FROM <MY_TABLE> GROUP BY name

Output:

AAA 2 duplicated
BBB 3 duplicated
CCC 1 not duplicated
查看更多
Anthone
6楼-- · 2019-01-17 16:16

For List:

SELECT COUNT(`name`) AS adet, name
FROM  `tbl` WHERE `status`=1 GROUP BY `name`
ORDER BY `adet`  DESC

Table View

For Total Count:

    SELECT COUNT(*) AS Total
    FROM (SELECT COUNT(name) AS cou FROM tbl GROUP BY name HAVING cou>1 ) AS virtual_tbl 

// Total: 5

查看更多
仙女界的扛把子
7楼-- · 2019-01-17 16:26

The approach is to have a nested query that has one line per duplicate, and an outer query returning just the count of the results of the inner query.

SELECT count(*) AS duplicate_count
FROM (
 SELECT name FROM tbl
 GROUP BY name HAVING COUNT(name) > 1
) AS t
查看更多
登录 后发表回答