SQL 查询、计数和分组依据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 23:04:43  来源:igfitidea点击:

SQL query, count and group by

sql

提问by Dan

If I have data like this:

如果我有这样的数据:

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

What is the SQL query to bring back the records where Nameis repeated 2 or more times?

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

So the result I would want is

所以我想要的结果是

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

回答by GateKiller

Couldn't be simpler...

不能更简单...

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

This could also be extended to delete duplicates:

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

Delete From Table
Where Key In (
    Select Max(Key)
        From Table
        Group By Name
        Having Count(Name) > 1
    )

回答by Ryan

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

回答by Dag Haavi Finstad

This could also be accomplished by joining the table with itself,

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

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