sql - 从每个组中选择 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
这样:
- 如果有 行
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)
我认为最整洁的是DISTINCT ON
推荐阅读
- reactjs - SSR:动态导入问题
- python - 为什么我的列表取另一个列表的值?
- python - Sympy 简化被破坏(平方根)?
- model - 如何从 mlr3tuning 的基准结果中提取具有调整超参数的最佳模型?
- javascript - 我的音频在更改当前时间时再次开始
- r - 有没有办法根据 R Shiny 中选定的 tabPanel 更新来自 tabsetPanel 中的 sliderInput 的输入?
- flutter - Google Maps Flutter 手势 三指滑动
- javascript - DigitalGarden 笔记页面创建期间的 GraphQL 查询投诉
- javascript - 如何在 React js 中替换 ul 中的 li 元素
- powershell - 通过 Powershell 在 Microsoft Teams 中添加多个成员