Mysql Select 查询带限制

标签 mysql select greatest-n-per-group

我有美国邮政编码的 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

关于Mysql Select 查询带限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59389064/

相关文章:

mysql - MYSQL 中的规范化

javascript - 使用不同的 Controller 检索另一个页面上的选择选项

mysql获取唯一日期的总和

mysql - 每个类别选择 5 个子类别

mysql - 使用最小列值创建左连接?

mysql - 我怎样才能既使用 DISTINCT 又不关心一列的值?

php - 多选复选框显示表记录

php - 从数据透视表中获取特定列值

C++ IO/多路复用 TCP 服务器和 POSIX 线程

MySQL 标记系统 - 每月热门关键词