Database 比较日期,计算它们之间的差异,博士后
我为每个用户设置了一个日期列和一个余额列。每次用户进行事务处理时,都会在此表中添加一个新行。可能是用户在一天内进行了15次交易,而在5天内根本没有交易 像这个Database 比较日期,计算它们之间的差异,博士后,database,postgresql,postgresql-9.2,Database,Postgresql,Postgresql 9.2,我为每个用户设置了一个日期列和一个余额列。每次用户进行事务处理时,都会在此表中添加一个新行。可能是用户在一天内进行了15次交易,而在5天内根本没有交易 像这个 date balance 2017-06-01 95.63 2017-06-01 97.13 2017-06-01 72.14 2017-06-06 45.04 2017-06-08
date balance
2017-06-01 95.63
2017-06-01 97.13
2017-06-01 72.14
2017-06-06 45.04
2017-06-08 20.04
2017-06-09 10.63
2017-06-09 -29.37
2017-06-09 -51.35
2017-06-13 -107.55
2017-06-13 -101.35
2017-06-15 -157.55
2017-06-16 -159.55
2017-06-17 -161.55
目标是选择当天交易中的正、负交易,计算其平均值或最小值,并将其视为一笔交易。如果第二天没有交易,则应使用前一天的金额。
这意味着一个月内的每一天我都应该计算利息,如果余额没有更新,那么应该使用前一天的余额。
假设我的桌子看起来像
date balance
1/6/2017 72.14
6/2/2017 72.14
6/3/2017 72.14
6/4/2017 72.14
6/5/2017 72.14
6/6/2017 45.04
7/6/2017 45.04
8/6/2017 20.04
9/6/2017 -51.35
10/6/2017 -51.35
11/6/2017 -51.35
12/6/2017 -51.35
13/06/2017 -107.55
14/06/2017 -107.55
15/06/2017 -157.55
16/06/2017 -159.55
17/06/2017 -161.55
我添加了缺失的那些日子,并将重复的日子分组
完成此操作后,我可以选择正余额天数,例如8天,计算平均正余额,并将其乘以0.4%
8*58.8525*0.004=0.23
负平衡也应该如此。但负余额天数的利率不同,例如9乘以该天数内的平均负余额和8.49%
9*-99.90555556*0.00849=-0.848
因此,我的预期结果是只有这两列
Neg Pos
-0.848 0.23
我怎样才能在博士后做到这一点?函数重叠实际上没有帮助,因为我需要指定日期
此外,我也不知道该怎么做
循环日期,查看是否有重复项
查看缺失的天数,并使用这些缺失天数的上一个余额
请试试这个。。用表名替换表
with cte as
(
Select "date" as date
,min(balance) as balance
,lead("date") over(order by "date") next_date
,Coalesce(ABS("date" - lead("date") over(order by "date")),1) date_diff
from table
group by "date"
),
cte2 as
(
Select date_diff*balance as tot_bal , date_diff
from cte
Where balance > 0
),
cte3 as
(
Select date_diff*balance as tot_bal , date_diff
from cte
Where balance < 0
)
Select (sum(cte2.tot_bal) / sum(cte2.date_diff) ) * 0.004 as pos
,(sum(cte3.tot_bal) / sum(cte3.date_diff) ) * 0.00849 as neg
from cte2
,cte3;
请试试这个。。用表名替换表
with cte as
(
Select "date" as date
,min(balance) as balance
,lead("date") over(order by "date") next_date
,Coalesce(ABS("date" - lead("date") over(order by "date")),1) date_diff
from table
group by "date"
),
cte2 as
(
Select date_diff*balance as tot_bal , date_diff
from cte
Where balance > 0
),
cte3 as
(
Select date_diff*balance as tot_bal , date_diff
from cte
Where balance < 0
)
Select (sum(cte2.tot_bal) / sum(cte2.date_diff) ) * 0.004 as pos
,(sum(cte3.tot_bal) / sum(cte3.date_diff) ) * 0.00849 as neg
from cte2
,cte3;