Update top N values using PostgreSQL

后端 未结 2 2212
-上瘾入骨i
-上瘾入骨i 2021-02-19 07:47

I want to update the top 10 values of a column in table. I have three columns; id, account and accountrank. To get the top 10 values I can

2条回答
  •  忘掉有多难
    2021-02-19 08:12

    Sure, you can use your select statement in a subquery. Generating the rank-order isn't trivial, but here's at least one way to do it. I haven't tested this, but off the top of my head:

    update accountrecords
    set accountrank =
        (select count(*) + 1 from accountrecords r where r.account > account)
    where id in (select id from accountrecords order by account desc limit 10);
    

    This has the quirk that if two records have the same value for account, then they will get the same rank. You could consider that a feature... :-)

提交回复
热议问题