sql - PostgreSQL: Select only the first record per id based on sort order -
for following query need select first record lowest shape_type value (ranges 1 10). if have knowledge on how postgresql, please help. time.
select g.geo_id, gs.shape_type schema.geo g join schema.geo_shape gs on (g.geo_id=gs.geo_id) order gs.shape_type asc;
postgresql have nice syntax types of queries - distinct on:
select distinct on ( expression [, ...] ) keeps first row of each set of rows given expressions evaluate equal. distinct on expressions interpreted using same rules order (see above). note "first row" of each set unpredictable unless order used ensure desired row appears first.
so query becomes:
select distinct on(g.geo_id) g.geo_id, gs.shape_type schema.geo g join schema.geo_shape gs on (g.geo_id=gs.geo_id) order g.geo_id, gs.shape_type asc;
in general ansi-sql syntax (in rdbms window functions , common table expression, switched subquery) be:
with cte ( select row_number() over(partition g.geo_id order gs.shape_type) rn, g.geo_id, gs.shape_type schema.geo g join schema.geo_shape gs on (g.geo_id=gs.geo_id) ) select geo_id, shape_type cte rn = 1
Comments
Post a Comment