How to self-join table in a way that every record is joined with the “previous” record?

后端 未结 7 1249
清歌不尽
清歌不尽 2021-01-02 06:55

I have a MS SQL table that contains stock data with the following columns: Id, Symbol, Date, Open, High, Low, Close.

I would like to self-join the table

7条回答
  •  难免孤独
    2021-01-02 07:13

    One option is to use a recursive cte (if I'm understanding your requirements correctly):

    WITH RNCTE AS (
      SELECT *, ROW_NUMBER() OVER (PARTITION BY symbol ORDER BY date) rn
            FROM quotes
      ),
    CTE AS (
      SELECT symbol, date, rn, cast(0 as decimal(10,2)) perc, closed
      FROM RNCTE
      WHERE rn = 1
      UNION ALL
      SELECT r.symbol, r.date, r.rn, cast(c.closed/r.closed as decimal(10,2)) perc, r.closed
      FROM CTE c 
        JOIN RNCTE r on c.symbol = r.symbol AND c.rn+1 = r.rn
      )
    SELECT * FROM CTE
    ORDER BY symbol, date
    

    SQL Fiddle Demo

    If you need a running total for each symbol to use as the percentage change, then easy enough to add an additional column for that amount -- wasn't completely sure what your intentions were, so the above just divides the current closed amount by the previous closed amount.

提交回复
热议问题