【发布时间】:2013-07-03 19:46:16
【问题描述】:
我使用的是 PostgreSQL 9.1.9。
在我正在处理的项目中,一些最近的记录具有空列,因为在创建该行时该信息不可用。我有一个视图列出了属于组成员的行的总和。截至目前,该视图显示最近列的总和,如果这些是最近的值,则使用空值。例如,
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;
当前视图如下所示:
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)。根据我链接的this page,关于PL/SQL的first_value()函数:
如果结果集中的第一个值为 NULL,则函数返回 NULL,除非您指定 IGNORE NULLS。 如果您使用 IGNORE NULLS 参数,则 FIRST_VALUE 将返回在结果集中找到的第一个非空值。 (我摔倒 值是 null 然后它将返回 NULL。)
示例语法:FIRST_VALUE(表达式 [INGORE NULLS]) OVER (analytic_clause)
但是 PostgreSQL 的 first_value() 不支持这样的选项。有没有办法在 PostgreSql 中做到这一点?先感谢您!
【问题讨论】:
-
我刚刚包含了与视图一起使用的 sql 脚本。谢谢。
-
我不明白这个解释。你一直在写“最近的专栏”。您是否及时添加列? “最近的专栏”是什么意思?
-
在这种情况下,我有 stat_date,我想用它来确定最近的行。在此示例中,每个人有多行,但其中一些比其他行更新,具体取决于 stat_date
标签: postgresql