Skip to content
Advertisement

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

I have this table:

Dividends History Table

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”)

Can this be done purely in SQL?

Is there any way to perform this calculation within a reasonable amount of time, if I have like 3000 dates/rows?

Advertisement

Answer

You can use a window function:

If you can have multiple rows per date, then put this logic in an aggregation query:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement