用于查看所有先前行的SQL语句

时间:2017-01-17 18:41:22

标签: sql amazon-redshift

我有下表

create table interest_earning_assets (
  key integer
  month_of varchar(7),
  principal_distribution numeric(38,2),
  closed_loan_amount numeric(38,2)
);

数据看起来像这样

key month_of    principal_distribution  closed_loan_amount
24  2017-01     4133500.00              5984695.00
23  2016-12     12018303.93             26941275.40
22  2016-11     6043945.46              21239620.20
21  2016-10     2864195.39              20368518.20

我有两个要求。

  1. 总结closed_amount_values
  2. 对于每个月(目前为24个月,下个月为25个月,然后是26个等),我需要将closed_amount_values与前几个月所有的值相加,即

    2017-01 sum(closed_loan_amount for 2016-10 + 2016-11 + 2016-12 + 2017-01)
    2016-12 sum(closed_loan_amount for 2016-10 + 2016-11 + 2016-12)
    2016-11 sum(closed_loan_amount for 2016-10 + 2016-11) 
    2016-10 sum(closed_loan_amount for 2016-10 )  
    
    1. 减去closed_loan_amount到principal_distribution
    2. 的总和

      一旦得到总和值,我需要每月减去closed_loan_amount到principal_distribution的总和

      2017-01 principal_distribution for 2017-01 - sum(closed_loan_amount for 2016-10 + 2016-11 + 2016-12 + 2017-01)
      2016-12 principal_distribution for 2016-12 - sum(closed_loan_amount for 2016-10 + 2016-11 + 2016-12)
      2016-11 principal_distribution for 2016-11 - sum(closed_loan_amount for 2016-10 + 2016-11) 
      2016-10 principal_distribution for 2016-10 - sum(closed_loan_amount for 2016-10 )  
      

      Redshift不支持存储过程,我不熟悉Python。所以我试图使用滞后

      select month_of, closed_loan_amount, 
             lag(closed_loan_amount,1) over (order by month_of desc) as previous_month 
      from public.interest_earning_assets
      

      它有效,但只给我上个月的价值。我也在考虑使用CTE,但我今天刚刚完成了这项任务。我怎么能在SQL中做到这一点?

2 个答案:

答案 0 :(得分:1)

使用带有窗口规范的sum窗口函数查看所有先前的行以获取closed_loan_amount的总和并从principal_distribution中减去它。

select month_of, closed_loan_amount, 
 principal_distribution
-sum(closed_loan_amount) over (order by month_of desc rows between current row and unbounded following) as some_value
from public.interest_earning_assets

答案 1 :(得分:1)

试试这个:

SELECT [key], month_of,
       SUM(closed_loan_amount) OVER(ORDER BY month_of),
       principal_distribution + SUM(closed_loan_amount) OVER(ORDER BY month_of)
FROM interest_earning_assets

带有SUM子句的ORDER BY的窗口版本根据ORDER BY子句中出现的第二个字段定义的顺序计算字段的运行总计。