SQL查询获取多次出现的值
我需要查询数据库以显示表中姓氏出现超过 3 次的记录。示例:在我的学生表中,有 3 个姓氏为“Smith”的人,4 个姓氏为“Johnson”,1 个姓氏为“Potter”。我的查询应该显示姓氏为 Smith 和 Johnson 的记录,因为这些值出现的次数超过或等于 3 次。
谁能指点我这一点吗?我正在考虑使用 COUNT() 但我似乎不知道如何应用它?
I need to query my database to show the records inside my table where lastname occurs more than three times. Example: in my Students Table, there are 3 people with Lastname 'Smith', 4 with 'Johnson', and 1 with 'Potter'. My query should show the records of those with the lastnames Smith, and Johnson since these values occur more than or equal to 3 times.
Can anyone point me to this? I was thinking of using COUNT() but I can't seem to think how to apply it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
来自 Oracle(但适用于大多数 SQL 数据库):
PS 它更快,因为这里没有使用 Select 方法进行选择
From Oracle (but works in most SQL DBs):
P.S. it's faster one, because you have no Select withing Select methods here
对于 SQL Server 2005+
For SQL Server 2005+
对于 MySQL:
For MySQL:
这里提到的答案非常优雅 https://stackoverflow.com/a/6095776/1869562 但经过测试,我意识到它只返回姓氏。
如果您想返回整个记录本身怎么办?
这样做
(对于 MySQL)
The answers mentioned here is quite elegant https://stackoverflow.com/a/6095776/1869562 but upon testing, I realize it only returns the last name.
What if you want to return the entire record itself ?
Do this
(For Mysql)
对于 PostgreSQL:
For postgresql:
我认为这个答案也可以工作(不过可能需要一些修改):
I think this answer can also work (it may require a little bit of modification though) :