在 Postgres 中,我的表中有一个记录列表,我知道这些记录是重复的。鉴于此重复列表
(id IN (1,2,3,4)
),我想使用以下优先级规则(从最高优先级到最低优先级)将它们组合成一条记录:
- 非 NULL 值
force=true
的记录值- 具有最新
更新
值的记录
例如:
应该变成这样:
最佳答案
我想你需要这样的东西:
select distinct
first_value(col1) filter (where col1 is not null) over (order by force desc, updated desc) as col1,
first_value(col2) filter (where col2 is not null) over (order by force desc, updated desc) as col2,
first_value(col3) filter (where col3 is not null) over (order by force desc, updated desc) as col3,
first_value(col4) filter (where col4 is not null) over (order by force desc, updated desc) as col4
from t
where id in (1, 2, 3, 4);
我不太喜欢使用窗口函数的select distinct
,但 Postgres 还没有提供 first_value()
作为聚合函数。
您也可以使用 array_agg()
做类似的事情。
编辑:
我没有意识到 filter
不适用于 first_value()
。啊。 array_agg()
形式是:
select (array_agg(column1 order by force desc, updated desc) filter (where column1 is not null))[1] as column1,
(array_agg(column2 order by force desc, updated desc) filter (where column2 is not null))[1] as column2,
(array_agg(column3 order by force desc, updated desc) filter (where column3 is not null))[1] as column3
from test_table;
Here是 SQL fiddle 。
关于sql - 使用优先规则将多行合并为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51672501/