繁体   English   中英

PostgreSQL:根据排序顺序仅选择每个id的第一条记录

[英]PostgreSQL: Select only the first record per id based on sort order

对于以下查询,我只需要选择shape_type值最小的第一条记录(范围从1到10)。 如果你有任何关于如何轻松做到这一点的知识是postgresql,请帮忙。 谢谢你的时间。

select g.geo_id, gs.shape_type
from schema.geo g   
join schema.geo_shape gs on (g.geo_id=gs.geo_id)  
order by gs.shape_type asc;

PostgreSQL对这类查询有非常好的语法 - 不同于

SELECT DISTINCT ON(expression [,...])仅保留给定表达式求值的每组行的第一行。 使用与ORDER BY相同的规则解释DISTINCT ON表达式(参见上文)。 请注意,每个集合的“第一行”是不可预测的,除非使用ORDER BY来确保首先出现所需的行。

所以你的查询变成:

select distinct on(g.geo_id)
    g.geo_id, gs.shape_type
from schema.geo g   
    join schema.geo_shape gs on (g.geo_id=gs.geo_id)  
order by g.geo_id, gs.shape_type asc;

一般来说,ANSI-SQL语法(在具有窗口函数和公用表表达式的任何RDBMS中,可以切换到子查询)将是:

with cte as (
    select
        row_number() over(partition by g.geo_id order by gs.shape_type) as rn,
        g.geo_id, gs.shape_type
    from schema.geo g   
        join schema.geo_shape gs on (g.geo_id=gs.geo_id)  
)
select
    geo_id, shape_type
from cte
where rn = 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM