使用 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
一行,这样:
- 如果有
foo = A
的行,取它, - 否则从该组中取出任何行?
示例输出:
group | foo | value
------+-----+------
1 | A | a
2 | A | a2
3 | B | b3 <- chosen one row from group 3
最佳答案
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)
我认为neatest将是 DISTINCT ON
关于sql - 从每个组中选择 1 行匹配或后备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50504974/