合并postgres中的字段聚合

时间:2017-06-21 15:43:36

标签: postgresql aggregate coalesce

我正在尝试按name字段进行分组,但是有一行可能具有的其他值的“合并聚合”。这是数据:

name        | jurisdiction    | db_from
------------|-----------------|----------------
my station    NULL              2017-06-21 8:01
my station    my jurisdiction   2017-06-21 8:00
my station    old data          2017-06-21 7:59

我想结束:

name        | jurisdiction    
------------|-----------------
my station    my jurisdiction  

以下是我的想法:

WITH _stations AS (
    SELECT * FROM config.stations x ORDER BY x.db_from DESC
)SELECT 
    x."name",
    (array_remove(array_agg(x.jurisdiction), NULL))[1] as jurisdiction
FROM _stations x
GROUP BY
    x."name";

jurisdiction字段的某些值可能为null,我正在尝试使用最近的非空值。

我知道我不应该依赖CTE的顺序,但它现在似乎在起作用。

2 个答案:

答案 0 :(得分:1)

我花了一点时间才想找到这个,所以我希望它有所帮助。如果这不是解决问题的最佳方法,请告诉我们:

SELECT 
    x."name",
    (array_remove(array_agg(x.jurisdiction ORDER BY x.db_from DESC), NULL))[1] as jurisdiction
FROM config.stations x
GROUP BY x."name" 

答案 1 :(得分:0)

select distinct on (x."name")
  *
from
  _stations x
where
  x.jurisdiction is not null
order by
  x."name", x.db_from desc

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT