UPDATE statement to re-assign a column value according to a numeric formula

前端 未结 1 775
梦谈多话
梦谈多话 2020-12-22 06:23

Given a table that would have values like this:

name, sortval, dept

bob,   2,       1
tom,   4,       1
mary,  6,       1
sam,   8,       1
tim,  10,                


        
相关标签:
1条回答
  • 2020-12-22 06:37

    A CASE statement may help. In this example:

    • the source, sam, is at position 8
    • the target, bob, is at position 2

    Replacing the variables with the actual values, the following statement shifts everything down 2 from the source, leaves the between members as is, sets the target equal to source, moves the rest down:

    postgres=> SELECT * FROM test order by sortval;
     name | sortval
    ------+---------
     bob  |       2
     tom  |       4
     mary |       6
     sam  |       8
     tim  |      10
    (5 rows)
    
    
    postgres=>      UPDATE test
    postgres->        SET sortval = CASE WHEN sortval <= 2 THEN sortval - 2
    postgres->                           WHEN sortval = 8  THEN 2
    postgres->                           WHEN sortval >= 8 THEN sortval - 2
    postgres->                           ELSE sortval
    postgres->                           END;
    UPDATE 5
    postgres=> SELECT * FROM test order by sortval;
     name | sortval
    ------+---------
     bob  |       0
     sam  |       2
     tom  |       4
     mary |       6
     tim  |       8
    (5 rows)
    

    That would move something up the list. Similar logic could be applied for moving down a list. And it assumes negative numbers are fine an that just the relative ordering is of interest.

    0 讨论(0)
提交回复
热议问题