This question is about SQL syntax for Postgres 12.
Let's assume a stock_prices
table with the following columns: ticker
, date
, price
.
I'm interested in performing calculation on the previous 10-day window, such as:
SELECT
ticker,
date,
price,
AVG(price)
OVER (PARTITION BY ticker ORDER BY date ROWS BETWEEN 10 PRECEDING AND 1 PRECEDING) as avg_previous_10d
FROM stock_prices
In addition to the simple average calculation above, I'd like to perform calculations on records within the previous 10-day window that satisfy conditions related to the current record. Specifically, within the previous 10-day window:
- Count the number of times the price was higher than the current row's price
- Calculate the average of prices that were higher than the current row's price
- Find the first time the price was higher than the current row's price
And so on.
I understand that I could perform a self join, such as the answer to this question. My question is - is there a straightforward way to do this using the window functions syntax? Or is self join the only way to go?
Thanks!