postgresql - 最近非空列的总和(带有 "ignore nulls"的窗口函数)

标签 postgresql

我使用的是 PostgreSQL 9.1.9。

在我正在处理的项目中,一些最新记录具有空列,因为创建该行时该信息不可用。我有一个 View ,列出了属于组成员的行的总和。截至目前,该 View 显示最新列的总和,如果这些是最新值,则使用空值。例如,

table1

group_name | member
-------------------
group1     | Andy
group1     | Bob

table2

name | stat_date | col1 | col2 | col 3
--------------------------------------
Andy | 6/19/13   | null |    1 |     2
Andy | 6/18/13   |  100 |    3 |     5
Bob  | 6/19/13   |   50 |    9 |    12
Bob  | 6/18/13   |  111 |   31 |    51

-- creating view would be something like this... 
create view v_grouped as 
select table1.group_name, stat_date, 
sum(col1) as col1_sum, sum(col2) as col2_sum, sum(col3) as col3_sum
from table1
join table2 on table1.member = table2.name
group by table1.group_name, table2.stat_date;

当前 View 如下所示:

group_name | stat_date | col1_sum | col2_sum | col3_sum
-------------------------------------------------------
group1     | 6/19/13   |       50 |       10 |       14
group2     | 6/18/13   |      211 |       34 |       56

尽管缺乏 6/19 的数据,但 150 人比 50 人更能代表实际的团体总数。所以,我想要一个输出

group_name | stat_date | col1_sum | col2_sum | col3_sum
-------------------------------------------------------
group1     |   6/19/13  |     150 |       10 |       14
group2     |   6/18/13  |     211 |       34 |       56

我一直在将窗口函数中的 first_value() 视为可能使用的函数。我发现 Oracle 的 first_value() 支持 ignore nulls 选项,我相信该选项可以实现我想要的功能 ( http://psoug.org/definition/FIRST_VALUE.htm )。根据我链接的此页面,关于 PL/SQL 的 first_value() 函数:

If the first value in the result set is NULL then the function returns NULL unless you specify IGNORE NULLS. If you use the IGNORE NULLS parameter then FIRST_VALUE will return the first non-null value found in the result set. (If all values are null then it will return NULL.)

Example Syntax: FIRST_VALUE(expression [INGORE NULLS]) OVER (analytic_clause)

但是 PostgreSQL 的 first_value() 不支持这样的选项。有没有办法在 PostgreSql 中做到这一点?先感谢您!

最佳答案

您可以使用this自定义聚合作为 FIRST_VALUE(expression INGORE NULLS) 的 postgres 变体。或者构建您自己的具有所需行为的聚合。

关于postgresql - 最近非空列的总和(带有 "ignore nulls"的窗口函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17456846/

相关文章:

java - 登录角色与用户密码表

sql - Postgresql - 具有相关子查询的条件 SUM

通过 SSH 隧道的 PostgreSQL

sql - 删除具有特定状态值的行(客户)

php - Doctrine (postgresql) Pessimistic Locking - 不会抛出 PessimisticLockException

macos - PostgreSQL 服务器不会在 Lion (Mac OS 10.7) 上关闭

java - Java Hibernate 中最后插入的 Id

postgresql - 在 postgresql 中引发异常

java - 如何在 pl/pgsql 中创建返回 refcursor 和totalRow 的函数/过程?

sql - 如何重写查询以将数据修改 CTE 置于顶层