如何使用红移中的SQL引用同一列的前一行中的值?

如何使用红移中的SQL引用同一列的前一行中的值?,sql,amazon-redshift,Sql,Amazon Redshift,我的背景是Excel建模,对SQL非常陌生。我有一张如下所示的桌子。我想创建“期望值”,该值假设预测月份的月复合增长率为1%: region | category | date | date_type | revenue | desired_col --------------------------------------------------------------------- East | Inventory | 07/2017 | Actual

我的背景是Excel建模,对SQL非常陌生。我有一张如下所示的桌子。我想创建“期望值”,该值假设预测月份的月复合增长率为1%:

region | category       | date    | date_type | revenue | desired_col
---------------------------------------------------------------------
East   | Inventory      | 07/2017 | Actual    | 25      | 25
East   | Non-Inventory  | 07/2017 | Actual    | 20      | 20
West   | Inventory      | 07/2017 | Actual    | 18      | 18
West   | Non-Inventory  | 07/2017 | Actual    | 16      | 16
East   | Inventory      | 08/2017 | Forecast  | 0       | 25.25
East   | Non-Inventory  | 08/2017 | Forecast  | 0       | 20.2
West   | Inventory      | 08/2017 | Forecast  | 0       | 18.18
West   | Non-Inventory  | 08/2017 | Forecast  | 0       | 16.16
East   | Inventory      | 09/2017 | Forecast  | 0       | 25.5025
East   | Non-Inventory  | 09/2017 | Forecast  | 0       | 20.402
West   | Inventory      | 09/2017 | Forecast  | 0       | 18.3618
West   | Non-Inventory  | 09/2017 | Forecast  | 0       | 16.3216
现在,我可以使用滞后函数在预测的第一个月(在上面的示例中为8月)完成这项工作:

CASE WHEN date_type = 'Actual' THEN revenue ELSE 
LAG( revenue , 1 ) OVER ( PARTITION BY region, category ORDER BY date ) * 1.01
END

但是上面的语句在9月份及以后返回0。这在Excel中很简单,但我在这里被难住了。你能给我什么建议吗?谢谢

从9月起,滞后声明不起作用,因为滞后(1)将关注8月的零收入。9月将使用8月的零计算,10月将使用9月的零计算,等等

您需要像这样循环LAG语句:

LAG( LAG( revenue , 1 ) OVER ( PARTITION BY region, category ORDER BY date ) * 1.01 , 1 ) OVER ( PARTITION BY region, category ORDER BY date ) * 1.01
…但你需要在未来的几个月里,按照你的预测来做。也就是说,非常混乱


我认为您将不得不使用一个循环和变量(就像unsql那样)。但好消息是,它更符合您熟悉的Excel解决方案。

您可以根据上一个实际月和预测月之间的月数确定必要的补偿,并将其用作
滞后
和增长率的动力的动态补偿:

with 
get_offsets as (
    select *
    ,case when to_date(date,'MM/YYYY')>'2017-07-01' then datediff(month,'2017-07-01',to_date(date,'MM/YYYY'))::integer end as this_offset
    from your_table
)
select *
,case when date_type = 'Actual' then revenue 
 else lag(revenue, this_offset) over (partition by region, category order by date) * 1.01 ^ this_offset
 end
from get_offsets

太好了,非常感谢!我能够用LAG(revenue,DATEDIFF(…)…^(DATEDIFF(…)将其插入到专栏中