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

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

    You could do something like this:

    DECLARE @Today DATETIME
    SELECT @Today = DATEADD(DAY, 0, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP))
    
    ;WITH today AS
    (
        SELECT  Id ,
                Symbol ,
                Date ,
                [OPEN] ,
                High ,
                LOW ,
                [CLOSE],
                DATEADD(DAY, -1, Date) AS yesterday 
        FROM quotes
        WHERE date = @today
    )
    SELECT *
    FROM today
    LEFT JOIN quotes yesterday ON today.Symbol = yesterday.Symbol
        AND today.yesterday = yesterday.Date
    

    That way you limit your "today" results, if that's an option.

    EDIT: The CTEs listed as other questions may work well, but I tend to be hesitant to use ROW_NUMBER when dealing with 100K rows or more. If the previous day may not always be yesterday, I tend to prefer to pull out the check for the previous day in its own query then use it for reference:

    DECLARE @Today DATETIME, @PreviousDay DATETIME
    SELECT @Today = DATEADD(DAY, 0, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP));
    SELECT @PreviousDay = MAX(Date) FROM quotes  WHERE Date < @Today;
    WITH today AS
    (
        SELECT  Id ,
                Symbol ,
                Date ,
                [OPEN] ,
                High ,
                LOW ,
                [CLOSE]
        FROM quotes 
        WHERE date = @today
    )
    SELECT *
    FROM today
    LEFT JOIN quotes AS previousday
        ON today.Symbol = previousday.Symbol
        AND previousday.Date = @PreviousDay
    

提交回复
热议问题