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

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

    You do something like this:

    with OrderedQuotes as
    (
        select 
            row_number() over(order by Symbol, Date) RowNum, 
            ID, 
            Symbol, 
            Date, 
            Open, 
            High, 
            Low, 
            Close
          from Quotes
    )
    select
        a.Symbol,
        a.Date,
        a.Open,
        a.High,
        a.Low,
        a.Close,
        a.Date PrevDate,
        a.Open PrevOpen,
        a.High PrevHigh,
        a.Low PrevLow,
        a.Close PrevClose,
    
        b.Close-a.Close/a.Close PctChange
    
      from OrderedQuotes a
      join OrderedQuotes b on a.Symbol = b.Symbol and a.RowNum = b.RowNum + 1
    

    If you change the last join to a left join you get a row for the first date for each symbol, not sure if you need that.

    0 讨论(0)
提交回复
热议问题