如何在Mysql中的多个列中找到重复值?

时间:2018-03-27 11:37:30

标签: mysql database-design count duplicates

我有一张这样的表

enter image description here

我想检查列A中列B的所有行,并获取重复计数。

例如,我想获得

count of 12 as 3(2 times in A+1 time in B)   
count of 11 as 2(2 times in A+0 time in B)   
count of 13 as 2(1 time in A+0 time in B)   

我怎样才能实现它?

2 个答案:

答案 0 :(得分:2)

您可以从union all计算总出现次数。 where子句只能显示A列中出现的值:

select  nr
,       count(*)
from    (
        select  A as nr
        from    YourTable
        union all
        select  B
        from    YourTable
        ) sub
where   nr in -- only values that occur at least once in the A column
        (
        select  A
        from    YourTable
        )
group by
        nr
having  count(*) > 1  -- show only duplicates

答案 1 :(得分:1)

您可以合并A和B中的所有值,然后执行分组。 然后只选择在A列中找到的那些值。

Select A, count(A) as cnt
From (
  Select A
  from yourTable
  Union All
  Select B 
  from yourTable) t
Where t.A in
(select distinct A from yourTable)
Group by t.A
Order by t.A;

结果:

A   cnt
11  2
12  3
13  1

请参阅演示:http://sqlfiddle.com/#!9/9fcfe9/3