26

我有桌子,结构如下。

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

返回此结果的查询:

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

与 AAA 和 BBB 重复的名称。我想要的最终结果是对这些重复记录的计数。

结果应该是这样的: 重复产品总数(2

4

7 回答 7

45

方法是有一个嵌套查询,每个重复一行,外部查询只返回内部查询结果的计数。

SELECT count(*) AS duplicate_count
FROM (
 SELECT name FROM tbl
 GROUP BY name HAVING COUNT(name) > 1
) AS t
于 2012-09-21T10:24:16.067 回答
14

使用 IF 语句获得所需的输出:

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

输出:

AAA 2 duplicated
BBB 3 duplicated
CCC 1 not duplicated
于 2012-09-21T10:29:55.473 回答
13

对于列表:

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

表视图

对于总计数:

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

// 总计:5

于 2016-02-22T10:25:21.300 回答
11

为什么不把它包装在一个子查询中:

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

请参阅带有演示的 SQL Fiddle

于 2012-09-21T10:23:48.027 回答
6

接受的答案计算有重复的行数,而不是重复的数量。如果要计算重复的实际数量,请使用:

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

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

) x

这样做是将分组中的重复项加起来,然后减去具有重复项的记录数量。原因是按总计分组并非所有重复项,每个分组的一条记录是唯一行。

小提琴:http ://sqlfiddle.com/#!2/29639a/3

于 2014-12-14T00:45:56.957 回答
0

SQL代码是:

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)
于 2015-11-28T12:01:37.027 回答
0

我在 PHP 中对我自己的表使用此查询,但它只给我一个结果,而我想要每个用户名的重复数量,这可能吗?

SELECT count(*) AS duplicate_count
FROM (
 SELECT username FROM login_history
 GROUP BY username HAVING COUNT(time) > 1
) AS t;
于 2022-02-16T11:21:29.993 回答