Sar*_*ist 14 sql postgresql distinct greatest-n-per-group distinct-on
对于以下查询,我只需要选择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;
Run Code Online (Sandbox Code Playgroud)
Rom*_*kar 27
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;
Run Code Online (Sandbox Code Playgroud)
一般来说,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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13880 次 |
最近记录: |