rshar :
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
Gordon Linoff :
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