Mysql if statement in select between two data

I have the following data in my query :

Year | Entitle  | 
2020 | 4        | 
2021 | 2        | 

How to do the conditional query if 'Entitle' is greater than other year then it will appear in new column. For example :

Year | Entitle  | Higher 
2020 | 4        | Yes
2021 | 2        | No

1 answer

  • answered 2021-01-11 05:44 Dobromir Velev

    I would probably use variables but then the order will different since than you will be comparing against the previous row.

    set @olden:=NULL;
    select year,entitle,
      if(isnull(@olden),"n/a",if(entitle>@olden,"yes","no")) as higher,
      @olden:=entitle 
    from table order by year;
    

    Please note that assigning variables in a SELECT statement may not work in future MySQL versions