SQL查询,计数和分组

如果我有这样的数据:

+---+----+
|Key|Name|
+---+----+
|1  |Dan |
+---+----+
|2  |Tom |
+---+----+
|3  |Jon |
+---+----+
|4  |Tom |
+---+----+
|5  |Sam |
+---+----+
|6  |Dan |
+---+----+

什么是SQL查询以将 Name 重复2次或更多次的记录带回来?

所以我想要的结果是

 +---+
 |Tom|
 +---+
 |Dan|
 +---+
0
额外 编辑
意见: 1

3 答案

不能更简单...

Select
Name,
Count(Name) As Count
From
Table
Group By
Name
Having
Count(Name) > 1
Order By
Count(Name) Desc

这也可以扩展为删除重复项:

Delete
From
Table
Where
Key In (
    Select
    Max(Key)
    From
    Table
    Group By
    Name
    Having
Count(Name) > 1)
0
额外
对于删除,您应该只保留最小值(键)并删除其他条目。查询应该修改为“...其中密钥NOT IN(选择Min(Key)....”
额外 作者 aartist,
select name from table group by name having count(name) > 1
0
额外

这也可以通过将表格与自身结合来完成,

SELECT DISTINCT t1.name
FROM    tbl t1
        INNER JOIN tbl t2
        ON      t1.name = t2.name
WHERE   t1.key         != t2.key;
0
额外