PostgreSQL更新值为最大值+ 1

时间:2012-01-13 17:53:02

标签: sql postgresql sequence

我需要在下表更新 因此,第3列中的值应等于最大值+1(对于每个A,其中B = 339)

            A  |        B    |   C  
         14430 |         339 |    -1     (value c should = 3)
         14430 |          80 |     0
         14430 |         262 |     1
         14430 |          39 |     2

         14431 |         339 |    -1     (value c should = 1)           
         14431 |          41 |     0

         14432 |         339 |    -1     (value c should = 0)   

         14433 |         284 |     0 
         14452 |         298 |     0
         14452 |         181 |     1

         14490 |         339 |    -1     (value c should = 0)   

         14491 |         339 |    -1     (value c should = 0) 

         14492 |         339 |    -1     (value c should = 0) 

1 个答案:

答案 0 :(得分:3)

UPDATE tbl
SET    c = x.new_c
FROM (
    SELECT a, max(c) + 1 AS new_c
    FROM   tbl
    -- WHERE  b <> 339  -- exclude b = 339 from calculating the maximum?
    GROUP  BY a
    ) x
WHERE  tbl.b = 339
AND    tbl.a = x.a
AND    tbl.c IS DISTINCT FROM x.new_c  -- to avoid pointless updates