简体   繁体   中英

Query to store order as value in postgresql

I have this simple table of players

id | name | score | place

I would like to know if there is a query that would let me sort the players by score and update the place according to the order.

You can do this with update , assuming that id is unique on each row:

update players
    set place = p.new_place
    from (select p.*, row_number() over (order by score) as new_place
          from players p
         ) p
    where players.id = p.id;
UPDATE players
  SET place=ordered_place
 FROM (SELECT id, 'place' AS ordered_place
         FROM players
        ORDER BY score
      ) AS t1 
WHERE players.id=t1.id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM