2
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     ---
4

2 回答 2

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;

-> sqlfiddle

原始问题

问题是查询分组

GROUP  BY lower(name), number

由于第 3 行和第 4 行具有不同 number的 ,因此对于此查询,它们并不相同。

如果您想忽略此查询的不同数字,请尝试以下操作:

SELECT lower(name)
     , count(*) AS ct
FROM   tbl
GROUP  BY lower(name)
HAVING count(*) > 1;
于 2012-10-30T06:14:21.050 回答
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

SQL 小提琴示例 #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

SQL 小提琴示例 #2

输出#2:

| DUPLICATE_NAME | DUPLICATE_NUMBER |
-------------------------------------
|            Aaa |              111 |
|            Abb |           (null) |
|            cca |           (null) |
于 2012-10-30T06:23:40.637 回答