sql - 使用优先规则将多行合并为一行

标签 sql postgresql

在 Postgres 中,我的表中有一个记录列表,我知道这些记录是重复的。鉴于此重复列表 (id IN (1,2,3,4)),我想使用以下优先级规则(从最高优先级到最低优先级)将它们组合成一条记录:

  • 非 NULL 值
  • force=true 的记录值
  • 具有最新更新值的记录

例如:

enter image description here

应该变成这样:

enter image description here

Fiddle with schema here

最佳答案

我想你需要这样的东西:

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/

相关文章:

Java隐藏从数据库中检索到的空值

mysql - 将 SQL 查询从 Postgres 移动到 MariaDB 时出错

sql - 将 INTERVAL DAY(0) 格式化为 SECOND(0)

mysql - 使用 MySQL 选择最后 5 个条目的 SUM 的最大值?

mysql - 如何从外键中选择一行而不是更多? - - 通过...分组 - -

mysql - 是否仍在使用 XA/JTA 事务?

sql - 带有 nativeQuery 的 Spring Boot Query 注释在 Postgresql 中不起作用

python - 创建具有 REAL 值(包括 UNIQUE 约束)的 SQLITE 表的最佳方法是什么?

sql - 减少 CTE 表中的记录数

postgresql - 使一个值首先出现在下拉其他值之后