简体   繁体   中英

Update table column based on multi row comparison operation in Postgres

I have following table in postgres

id          num
EBI-1002144 1
EBI-1002144 1
EBI-1002142 2
EBI-1002142 2
EBI-1002635 1
EBI-1002635 1
EBI-1002635 2
EBI-1002635 2
EBI-1003351 1
EBI-1003351 1
EBI-1003351 2
EBI-1003351 2
EBI-1003469 1
EBI-1003469 1
EBI-1003469 2
EBI-1003469 2
EBI-1003574 1
EBI-1003574 1
EBI-1003574 2
EBI-1003574 2

I want to append another column to this table based on following conditions:

--> group by id 
--> calculate max of num
--> if the value of num > 1 per id, then assign the id as label 'A' else 'B'

I am able to find out the max value but unable to figure out how to assign the value to each row with common id.

The expected output is:

id          num  label
EBI-1002144 1    B
EBI-1002144 1    B
EBI-1002142 1    A
EBI-1002142 2    A
EBI-1002635 1    A
EBI-1002635 1    A
EBI-1002635 2    A
EBI-1002635 2    A
EBI-1003351 1    A
EBI-1003351 1    A
EBI-1003351 2    A
EBI-1003351 2    A
EBI-1003469 1    A
EBI-1003469 1    A
EBI-1003469 2    A
EBI-1003469 2    A
EBI-1003574 1    A
EBI-1003574 1    A
EBI-1003574 2    A
EBI-1003574 2    A

Use window functions:

select t.*,
       (case when max(num) over (partition by id) > 1 then 'A' else 'B' end) as label
from t;

If you actually want to update the table, aggregate and join :

update t
    set label = (case when max_num > 1 then 'A' else 'B' end)
    from (select id, max(num) as max_num
          from t 
          group by id
         ) tt
    where tt.id = t.id

You can use window functions.

If you want an update statement:

with cte as (
    select 
        id,
        case 
            when max(num) over(partition by id) > 1 
            then 'A' 
            else 'B' 
        end label
    from mytable t
)
update mytable 
set label = cte.label
from cte 
where cte.id = mytable.id

If you want a select :

select 
    t.*,
    case 
        when max(num) over(partition by id) > 1 
        then 'A' 
        else 'B' 
    end label
from mytable t

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