查询将顺序存储为postgresql中的值

时间:2017-05-29 12:09:24

标签: sql postgresql

我有这个简单的玩家表

id | name | score | place

我想知道是否有查询可让我按score对玩家进行排序,并根据订单更新place

2 个答案:

答案 0 :(得分:1)

您可以使用update执行此操作,假设每行id都是唯一的:

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;

答案 1 :(得分:1)

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;