SELECT count(*), lower(name), number
FROM tbl
GROUP BY lower(name), number
HAVING count(*) > 1;
输入tb1
slno name number
1 aaa 111
2 Aaa 111
3 abb 221
4 Abb 121
5 cca 131
6 cca 141
7 abc 222
8 cse 222
这个查询只能找到相同的数字和名称中的重复项,但它不能在第3行和第4行找到重复项!!!
SELECT count(*), lower(name)
FROM tbl
GROUP BY lower(name)
HAVING count(lower(name)) > 1
此查询可以找到名称中的所有重复项!它完美地运作
SELECT count(*), number
FROM tbl
GROUP BY number
HAVING count(number) > 1
此查询可以找到所有重复的数字!它完美地运作
我想要一个查询,它可以找到名称和数字中的所有重复项,无论名称是小写还是大写
output
name number count
2 111 aaa
2 --- abb
2 --- cca
2 222 ---
答案 0 :(得分:5)
“在数字和名称上都重复”......“名称和编号为不同的列”
行可以在这里计算两次!
SELECT lower(name), NULL AS number, count(*) AS ct
FROM tbl
GROUP BY lower(name)
HAVING count(*) > 1
UNION ALL
SELECT NULL, number, count(*) AS ct
FROM tbl
GROUP BY number
HAVING count(*) > 1;
问题是查询按
分组GROUP BY lower(name), number
由于第3行和第4行的不同 number
,因此对于此查询,它们并不相同。
如果要忽略此查询的不同数字,请尝试以下操作:
SELECT lower(name)
, count(*) AS ct
FROM tbl
GROUP BY lower(name)
HAVING count(*) > 1;
答案 1 :(得分:1)
通过一些工作,我们可以在一列中显示name
和number
的计数:
select NameOrNumber, count(*) as Count
from (
select name as NameOrNumber from tb1
union all
select number from tb1
) a
group by NameOrNumber
having count(NameOrNumber) > 1
输出#1:
| NAMEORNUMBER | COUNT |
------------------------
| 111 | 2 |
| aaa | 2 |
| abb | 2 |
| cca | 2 |
如果您希望输出位于不同的列中,您可以执行以下操作:
select distinct if(t1.name = t2.name, t1.name, null) as DUPLICATE_Name,
if(t1.number = t2.number, t1.number, null) as DUPLICATE_Number
from tb1 t1
inner join tb1 t2 on (t1.name = t2.name or t1.number = t2.number)
and t1.slno <> t2.slno
输出#2:
| DUPLICATE_NAME | DUPLICATE_NUMBER |
-------------------------------------
| Aaa | 111 |
| Abb | (null) |
| cca | (null) |