SQL 查询、计数和分组依据

如果我有这样的数据:

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

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

所以我想要的结果是

 +---+
 |Tom|
 +---+
 |Dan|
 +---+
请先 登录 后评论

3 个回答

GateKiller

再简单不过了...

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)
请先 登录 后评论
Ryan
select name from table group by name having count(name) > 1
请先 登录 后评论
Dag Haavi Finstad

这也可以通过将表与自身连接来实现,

SELECT DISTINCT t1.name
FROM    tbl t1
        INNER JOIN tbl t2
        ON      t1.name = t2.name
WHERE   t1.key         != t2.key;
请先 登录 后评论