用于查看所有先前行的 SQL 语句
Posted
技术标签:
【中文标题】用于查看所有先前行的 SQL 语句【英文标题】:SQL statement to look at ALL the previous rows 【发布时间】:2017-01-17 18:41:21 【问题描述】:我有下表
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
与前几个月 all 的值相加,即
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
一旦我得到了汇总值,我需要将每个月的principal_distribution 减去closed_loan_amount
的总和
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 中做到这一点?
【问题讨论】:
sum(closed_loan_amount) over (order by month-of rows between unbounded preceding and current row)
我不知道 Redshift 支持这些操作的程度。 docs.aws.amazon.com/redshift/latest/dg/…
【参考方案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
【讨论】:
我需要学习像这样的窗口函数。我不知道我能做到这一点。谢谢你。接受并投票赞成。谢谢!!!【参考方案2】:试试这个:
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
带有ORDER BY
子句的SUM
的窗口版本根据ORDER BY
子句中出现的第二个字段定义的顺序计算字段的运行总计。
【讨论】:
以上是关于用于查看所有先前行的 SQL 语句的主要内容,如果未能解决你的问题,请参考以下文章