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

后端 未结 6 1565
抹茶落季
抹茶落季 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:34

    I considered id as primary key in the table (and as "row number"), and used it to compare each record with the record before. The following code must work.

    CREATE SCHEMA temp
    create table temp.emp (id integer,name varchar(50), salary  varchar(50));
    insert into temp.emp values(1,'a','25000');
    insert into temp.emp values(2,'b','30000');
    insert into temp.emp values(3,'c','35000');
    insert into temp.emp values(4,'d','40000');
    insert into temp.emp values(5,'e','45000');
    insert into temp.emp values(6,'f','20000');
    
    select * from temp.emp
    
    SELECT
        current.id, current.name, current.salary,
        case 
            when current.id = 1 then current.salary 
            else 
                case
                    when current.salary > previous.salary then previous.salary
                    else current.salary  
                end
         end
    FROM
        temp.emp AS current
        LEFT OUTER JOIN temp.emp AS previous
        ON current.id = previous.id + 1
    

提交回复
热议问题