首页 > 解决方案 > 从每个组中选择 1 行匹配或作为后备

问题描述

使用 PostgreSQL 9.6,如何从这样的数据中获取 I:

group | foo | value
------+-----+------
1     | A   | a
1     | B   | b
1     | C   | c
2     | B   | b2
2     | A   | a2
3     | B   | b3
3     | C   | c3

每排一排,group这样:

示例输出:

group | foo | value
------+-----+------
1     | A   | a
2     | A   | a2
3     | B   | b3 <- chosen one row from group 3

标签: sqlpostgresqlselect

解决方案


t=# select distinct on ("group") "group", foo, value 
from table
order by "group", foo = 'A' DESC;
 group  |  foo  | value
--------+-------+-------
 1      |  A    |  a
 2      |  B    |  b2
 3      |  B    |  b3
(3 rows)

我认为最整洁的是DISTINCT ON


推荐阅读