简体   繁体   English

查询在一次查询中计算 100 个日期的“尾随十二个月总和(列)”?

[英]Query to calculate “trailing twelve-month sum(column)” for 100s of dates in one query?

I have this table:我有这张桌子:

Dividends History Table股息历史表

id | date | dividends_received_value
 1 | 2020-01-02 | 0.00
 2 | 2020-01-03 | 1.30
 3 | 2020-01-04 | 0.45
...

I'm trying to figure out the most efficient way to get:我试图找出最有效的方法来获得:

  • One row for each date每个日期一行
  • Each row contains the每行包含

sum(dividends_received_value) for the past year of data relative to the date in that row ("trailing twelve months") sum(dividends_received_value)相对于该行日期的过去一年的数据(“过去十二个月”)

Can this be done purely in SQL?这可以纯粹在 SQL 中完成吗?

Is there any way to perform this calculation within a reasonable amount of time, if I have like 3000 dates/rows?如果我有 3000 个日期/行,有什么方法可以在合理的时间内执行此计算?

You can use a window function:您可以使用 window function:

select t.*,
       sum(dividends_received_value) over (order by date
                                           range between interval 1 year preceding and current row
                                          ) as trailing_12_month
from t;

If you can have multiple rows per date, then put this logic in an aggregation query:如果每个日期可以有多行,则将此逻辑放入聚合查询中:

select t.date, sum(dividends_received_value) as on_day,
       sum(sum(dividends_received_value)) over (order by date
                                                range between interval 1 year preceding and current row
                                               ) as trailing_12_month
from t
group by t.date;

Here is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM