sql - MySQL to calculate ranking and update the original table -


mysql server 5.6.20 (latest version @ moment)

given price date table. added new column "rank", represent ranking item price date.

date      item  price  rank 1/1/2014      5.01   0   1/1/2014  b     31     0   1/1/2014  c     1.5    0   1/2/2014      5.11   0   1/2/2014  b     20     0   1/2/2014  c     5.5    0   1/3/2014      30     0   1/3/2014  b     11.01  0   1/3/2014  c     22     0   

how write sql statement calculate ranking , update original table? below expected table ranking filled in. ranking calculation grouped date (1/1, 1/2, 1/3, etc).

date      item  price  rank 1/1/2014      5.01   2   1/1/2014  b     31     1   1/1/2014  c     1.5    3   1/2/2014      5.11   3   1/2/2014  b     20     1   1/2/2014  c     5.5    2   1/3/2014      30     1   1/3/2014  b     11.01  3   1/3/2014  c     22     2   

also, if price same several items, how mysql handle ranking? example:

date      item  price  rank 1/4/2014      31     0   1/4/2014  b     31     0   1/4/2014  c     1.5    0   

thanks.

you can rank in query using varibles:

  select t.*,          (@rn := if(@d = date, @rn + 1,                     if(@d := date, 1, 1)                    )          ) rank   pricebydate t cross join        (select @d := null, @rn := 0) vars   order date, price desc; 

you can put in update using join:

update pricebydate pbd join        (select t.*,              (@rn := if(@d = date, @rn + 1,                         if(@d := date, 1, 1)                        )              ) rank         pricebydate t cross join              (select @d := null, @rn := 0) vars         order date, price desc        ) r        on pbd.date = r.date , pbd.item = item     set pbd.rank = r.rank; 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -