基于Postgres中的多行比较操作更新表列

时间:2020-03-06 15:08:15

标签: sql postgresql group-by max

我在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

我想根据以下条件在此表中追加另一列:

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

我能够找到最大值,但无法弄清楚如何将值分配给具有公共ID的每一行。

预期输出为:

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

2 个答案:

答案 0 :(得分:1)

使用窗口功能:

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

如果您实际上要更新表,请汇总并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

答案 1 :(得分:0)

您可以使用窗口功能。

如果要使用update语句:

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

如果您想要select

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