sql pulling a row for next or previous row of a current row

后端 未结 6 1570
抹茶落季
抹茶落季 2020-12-03 05:51
id    |  photo title     |  created_date

XEi43 |  my family       |  2009 08 04
dDls  |  friends group   |  2009 08 05
32kJ  |  beautiful place |  2009 08 06
EOIk  |  wo         


        
6条回答
  •  悲&欢浪女
    2020-12-03 06:32

    Using Mike's MAX/MIN trick we can make previous\next jumps for all sorts of things. This msAccess example will return the previous close for every record in a stock market data table. Note: the '<=' is for weekends and holidays.

    SELECT 
       tableName.Date,
       tableName.Close,
       (SELECT Close 
          FROM tableName 
          WHERE Date = (SELECT MAX(Date) FROM tableName 
                         WHERE Date <= iJoined.yesterday)
       ) AS previousClose
    FROM 
     (SELECT Date, DateAdd("d",-1, Date) AS yesterday FROM tableName)
      AS iJoined 
    INNER JOIN 
        tableName ON tableName.Date=iJoined.Date;
    

    ...'yesterday' demonstrates using a function(Date-1) jump; we could have simply used...

    (SELECT Date FROM tableName) AS iJoined
      /* previous record */
    (SELECT MAX(Date) FROM tableName WHERE Date < iJoined.Date)
      /* next record */
    (SELECT MIN(Date) FROM tableName WHERE Date > iJoined.Date)
    

    The trick is we can previous\next # of whatever(s) with MAX\MIN and a jump function()

提交回复
热议问题