SQL) I'm trying to compare successive rows in SQL query using "date" as a key. Lead() method gives me syntax error

50 views Asked by At

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$
... ... ...
Google 2021-03-13 3000$
Google 2021-03-14 3900$
Google 2021-03-15 7800$
Google 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 syntax error from

...
FROM 
    comparing_price
WHERE
    100*(x1.close - x0.close)/x0.close >= '30'; 
1

There are 1 answers

6
Gordon Linoff On

No. lead() is much simpler:

SELECT dp.*,
       LEAD(price) OVER (PARTITION BY code ORDER BY date) as next_price,
       LEAD(price, 2) OVER (PARTITION BY code ORDER BY date) as next_price_2,
       LEAD(price, 3) OVER (PARTITION BY code ORDER BY date) as next_price_3
  FROM daily_price dp;

One caveat: This assumes that all codes have rows for each days. In a table called daily_price that seems like a reasonable assumption.