My Database include every weekdays for each stocks [daily_price]:
Stock | Date | Price |
---|---|---|
Apple | 2018-06-01 | 100$ |
Apple | 2018-06-02 | 130$ |
Apple | 2018-06-03 | 143$ |
Apple | 2018-06-04 | 286$ |
... | ... | ... |
2021-03-13 | 3000$ | |
2021-03-14 | 3900$ | |
2021-03-15 | 7800$ | |
2021-03-16 | 3900$ | |
... | ... | ... |
I want to make a query that looks like this:
(trying to see movements of the next 3 days of stocks that has gone up more than 30% on D+1)
Stock | From | To | D+1 % | D+2 % | D+3 % |
---|---|---|---|---|---|
Apple | 2018-06-02 | 2018-06-04 | +30% | +10% | +100% |
Apple | 2021-03-14 | 2021-03-16 | +30% | +100% | -50% |
My query [tried to used lead()] is as follows:
WITH comparing_price AS (
SELECT
CODE, DATE, OPEN, high, low, close, volume,
LEAD(daily_price, 1) OVER (PARTITION BY CODE ORDER BY DATE) AS x1,
LEAD(daily_price, 2) OVER (PARTITION BY CODE ORDER BY DATE) AS x2,
LEAD(daily_price, 3) OVER (PARTITION BY CODE ORDER BY DATE) AS x3
FROM daily_price x0
)
SELECT
x0.code as 'Stock',
x1.date as 'From',
x3.date as 'To',
100*(x1.close - x0.close)/x0.close AS 'D+1 %',
100*(x2.close - x1.close)/x1.close AS 'D+2 %',
100*(x3.close - x2.close)/x2.close AS 'D+2 %'
FROM
comparing_price
WHERE
100*(x1.close - x0.close)/x0.close >= '30';
My Table's primary keys are stock name [code] and date [date] from [daily_price] DB.
It gives me SQL error 1054: Unknown column 'daily_price' in 'field list'