Search code examples
sqlsql-serverinner-join

Get today and previous available date data in a single row


I have following table data for processing.

SYMBOL    DATE        OPENVALUE        CLOSEVALUE
-------------------------------------------------
ABC       2019-01-01  10               15
ABC       2019-01-02  17               19
ABC       2019-01-03  13               20
ABC       2019-01-04  18               30
ABC       2019-01-07  25               45
ABC       2019-01-08  40               50

I want to process and display information as follow

SYMBOL        DATE        OPENVALUE        PREVDAYCLOSINGVALUE
--------------------------------------------------------------
ABC           2019-01-01  10               NA
ABC           2019-01-02  17               15
ABC           2019-01-03  13               19
ABC           2019-01-04  18               20
ABC           2019-01-07  25               30
ABC           2019-01-08  40               45

If anyone can help. I am facing problem with inner joining current date with previous available date data.


Solution

  • You are looking for lag():

    select t.*,
           lag(closevalue) over (partition by symbol order by date) as prev_closevalue
    from t;