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

后端 未结 7 1268
清歌不尽
清歌不尽 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:07

    Index on (symbol, date)

    SELECT *
    FROM quotes q_curr
    CROSS APPLY (
      SELECT TOP(1) *
      FROM quotes
      WHERE symbol = q_curr.symbol
        AND date < q_curr.date
      ORDER BY date DESC
    ) q_prev
    

提交回复
热议问题