Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Postgres中基于多行比较操作的表列更新_Sql_Postgresql_Group By_Max - Fatal编程技术网

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

Sql Postgres中基于多行比较操作的表列更新,sql,postgresql,group-by,max,Sql,Postgresql,Group By,Max,我在博士后有下表 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 E

我在博士后有下表

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

您可以使用窗口函数

如果需要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 t.*,
       (case when max(num) over (partition by id) > 1 then 'A' else 'B' end) as label
from t;
如果确实要更新表,请聚合并联接:

select t.*,
       (case when max(num) over (partition by id) > 1 then 'A' else 'B' end) as label
from t;
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