PostgreSQL-完成系列

时间:2018-10-08 13:16:04

标签: sql postgresql

我有一个系列,这是一个简单的公式,其中x =昨天,y =三天前:

x + (x - y) / 2

在excel中,计算上述系列很容易。但是,这里是一个样本数据集,我希望根据之前的值完成一系列操作。请注意,实际数据仅来自数据集。所以我们有来自1/1 / 2018、1 / 2/2018和1/3/2018的数据。然后,根据上述公式,我们将预测1/4/2018至1/8/2018:

      A (dt)    B (sum)   excel equivalent
row1  1/1/2018  1         (actual)
row2  1/2/2018  2         (actual)
row3  1/3/2018  5         (actual)
row4  1/4/2018  7         (predicted) =B3 + ((B3 - B1) / 2)
row5  1/5/2018  9.5       (predicted) =B4 + ((B4 - B2) / 2)
row6  1/6/2018  11.75     (predicted) =B5 + ((B5 - B3) / 2)
row7  1/7/2018  14.125    (predicted) =B6 + ((B6 - B4) / 2)
row8  1/8/2018  16.4375   (predicted) =B7 + ((B7 - B5) / 2) 

我知道您可以通过使用Partition By来获得累积总和,但是如上所述,我在修改累积总和时遇到了麻烦。有没有办法在PostgreSQL中完成此任务?

这是excel的屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:3)

这是一个难题。这是使用递归CTE的解决方案:

with recursive cte as (
      select 1 as n, 1::numeric as x, null::numeric as x_1, null::numeric as x_2
      union all
      select n + 1, 
             (case n + 1 when 2 then 2 when 3 then 5
                   else x + (x - x_2) / 2
              end) as x,
             x as x_1, x_1 as x_2
      from cte 
      where n < 10
     )
select *
from cte;

db<>fiddle一起。

该想法是在单独的列中透视所需的历史值。请注意,公式是x + (x - x_2) / 2而不是x_1 + (x_1 - x_3) / 2,因为它使用的是上一个行中的值。