我有 table ,下面的结构 .
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
返回此结果的查询:
AAA(2) duplicate
BBB(3) duplicate
CCC(1) not duplicate
重复的名称为AAA和BBB . 最终结果,我想要的是这些重复记录的数量 .
结果应如下所示:重复产品总数( 2 )
6 回答
方法是使嵌套查询每个副本有一行,外部查询只返回内部查询结果的计数 .
为什么不将它包装在子查询中:
见SQL Fiddle with Demo
使用IF语句获得所需的输出:
输出:
For List:
For Total Count:
//总计:5
接受的答案 counts the number of rows that have duplicates ,而不是 amount of duplicates . 如果要计算 actual number of duplicates ,请使用:
这样做的总和是组中的重复项,但随后减去了具有重复项的记录数量 . 原因是group by total不是全部重复,每个分组的一个记录是唯一的行 .
小提琴:http://sqlfiddle.com/#!2/29639a/3
SQL代码是: