mysql - Mysql Select 有限制的查询
问题描述
我有美国邮政编码的 MySQL 表,例如
id | zip_code | city | State
1 | 99553 | Akutan | Alaska
2 | 99571 | Cold Bay | Alaska
3 | 99583 | False Pass | Alaska
4 | 36006 | Billingsley| Alabama
5 | 36008 | Booth | Alabama
6 | 36051 | Marbury | Alabama
......
我想使用单选 MySQL 查询为每个州仅获取 2 个城市,因此最终结果如下表所示
id | zip_code | city | State
1 | 99553 | Akutan | Alaska
2 | 99571 | Cold Bay | Alaska
4 | 36006 | Billingsley| Alabama
5 | 36008 | Booth | Alabama
解决方案
如果您正在运行 MySQL 8.0,则可以使用row_number()
:
select id, zip_code, city, state
from (
select t.*, row_number() over(partition by state order by zip_code) rn
from mytable t
) t
where rn <= 2
在早期版本中,您可以使用相关子查询进行过滤:
select t.*
from mytable t
where (
select count(*)
from mytable t1
where t1.state = t.state and t1.zip_code <= t.zip_code
) <= 2
推荐阅读
- sql - SQL查询准确搜索数字
- javascript - 未捕获的错误:找不到从“appName/resolver”导入的模块“ember-resolver”
- jupyter-notebook - 通过 cmd 行将 conda 环境添加到 jupyter 不起作用
- asp.net - 设置 Gridview 列宽
- python - 是否有可能以及如何在pygame中设置光标?(Python)
- html5-audio - 用于服务、流式传输和消费大型音频文件的基本架构,以最大限度地减少客户端资源消耗和延迟
- github - Github:如何解决挂起的拉取请求?
- html - 如何使用 Bootstrap 激活下拉菜单?
- bash - 码头工人执行卷曲帖子
- java - BufferedReader 无法读取 Google Cloud Storage ReadChannel 上的所有行