仅基于2列计算重复行

时间:2016-03-08 12:09:34

标签: mysql sql group-by duplicates having

假设我有一个名为test的下表,其中包含2列AB
A B
------
1 2
2 3
1 2
3 4
我想使用一个查询,该查询只返回基于AB列组合的重复行数(在本例中为1和3),因此返回的计数应为{{1} }。
2(查询在这里),谢谢。

4 个答案:

答案 0 :(得分:1)

SELECT A, B, COUNT(*) as Count FROM Test GROUP BY A, B HAVING COUNT(*) > 1

答案 1 :(得分:1)

如果我理解正确,如果你的例子中有另一行(2,3)那么计数应该是4.如果是这样,请使用:

SELECT 'Duplicates' as warning,sum(cnt) FROM (
    SELECT a,b,COUNT(*) as cnt
    FROM YourTable
    GROUP BY a,b
    HAVING count(*) > 1
)

答案 2 :(得分:1)

要成对使用,

SELECT CONCAT(A,'-',B) AS Duplicate Pair,COUNT(A) AS COUNT FROM `test` GROUP BY A,B HAVING COUNT(A) > 1;

OR 为了个人使用,

SELECT A AS Duplicate1,B AS Duplicate2,COUNT(A) AS COUNT FROM `test` GROUP BY A,B HAVING COUNT(A) > 1;

答案 3 :(得分:0)

您可以使用子查询:

select 'Duplicates' as warning, count(*) as rowcount
from (select a, b, count(*) as cnt
      from test t
      group by a, b
      having cnt > 1
     ) t;