如果我有这样的数据:

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

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

所以我想要的结果是

 +---+
 |Tom|
 +---+
 |Dan|
 +---+

===============>>#1 票数:38 已采纳

不能简单......

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)

===============>>#2 票数:4

select name from table group by name having count(name) > 1

===============>>#3 票数:3

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

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

  ask by Dan translate from so

未解决问题?本站智能推荐: