2017-01-17 40 views
1

我有以下表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 

我有兩個要求。

  1. 總結一下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中做到這一點?

    +2

    'sum(closed_loan_amount)over(按月排列的無界前行和當前行之間的行)'我不知道Redshift支持這些操作的數量。 http://docs.aws.amazon.com/redshift/latest/dg/r_Window_function_synopsis.html – shawnt00

    回答

    1

    使用帶窗口規範的sum窗口函數來查看所有前面的行,以獲取closed_loan_amount的總和並從principal_distribution中減去它。根據出現的ORDER BY子句中的第二字段中定義的順序

    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子句計算運行總計字段的:

    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 
    
    +0

    我需要了解這種窗口功能。我不知道我可以做到這一點。謝謝。接受並投票決定。謝謝!!! – Alan

    1

    嘗試此。

    相關問題