我有以下表SQL語句來看看以前所有的行
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
我有兩個要求。
- 總結一下
closed_amount_values
對於每個月(目前爲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)
- 減去的
closed_loan_amount
總和principal_distribution
一旦我有總結出來的價值觀,我需要減去的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)
紅移不支持存儲過程和我不是在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中做到這一點?
'sum(closed_loan_amount)over(按月排列的無界前行和當前行之間的行)'我不知道Redshift支持這些操作的數量。 http://docs.aws.amazon.com/redshift/latest/dg/r_Window_function_synopsis.html – shawnt00