在Oracle中如何查询组内的第一个值?在Postgres中,您可以使用
DISTINCT ON
查询组内的第一个值。根据Postgres手册所述,SELECT DISTINCT ON (expression [, ...])
仅保留指定表达式计算结果相等的一组行中的第一行。 DISTINCT ON
表达式的解释与ORDER BY
相同。请注意,每个集合的“第一行”是不可预测的,除非使用ORDER BY
确保所需行出现在首位。例如,对于给定的表: col1 | col2
------+------
A | AB
A | AD
A | BC
B | AN
B | BA
C | AC
C | CC
升序排序:
> select distinct on(col1) col1, col2 from tmp order by col1, col2 asc;
col1 | col2
------+------
A | AB
B | AN
C | AC
降序排序:
> select distinct on(col1) col1, col2 from tmp order by col1, col2 desc;
col1 | col2
------+------
A | BC
B | BA
C | CC
first_value()
变体是对DISTINCT ON
的巧妙模拟。我应该将其构建到 jOOQ 中。 - Lukas Eder