【发布时间】:2015-06-07 15:57:18
【问题描述】:
我在 Postgres 中有以下场景(我正在使用 9.4.1)。
我有一个这种格式的表格:
create table test(
id serial,
val numeric not null,
created timestamp not null default(current_timestamp),
fk integer not null
);
然后我拥有的是另一个表中的threshold numeric 字段,该字段应该用于标记test 的每一行。对于>= threshold 的每个值,我希望将该记录标记为true,但如果它是true,它应该在那时将后续计数重置为0,例如
数据集:
insert into test(val, created, fk)
(100, now() + interval '10 minutes', 5),
(25, now() + interval '20 minutes', 5),
(30, now() + interval '30 minutes', 5),
(45, now() + interval '40 minutes', 5),
(10, now() + interval '50 minutes', 5);
阈值为 50,我希望输出为:
100 -> true (as 100 > 50) [reset]
25 -> false (as 25 < 50)
30 -> true (as 25 + 30 > 50) [reset]
45 -> false (as 45 < 50)
10 -> true (as 45 + 10 > 50)
是否可以在单个 SQL 查询中执行此操作?到目前为止,我已经尝试过使用window function。
select t.*,
sum(t.val) over (
partition by t.fk order by t.created
) as threshold_met
from test t
where t.fk = 5;
如您所见,我已经达到了累积频率的程度,并且怀疑rows between x preceding and current row 的调整可能是我正在寻找的。我只是不知道如何执行重置,即将上面的x设置为适当的值。
【问题讨论】:
-
很好的问题,包含所有必要的细节。请多提这样的问题。 :)
标签: sql postgresql aggregate-functions aggregate window-functions