SQL 重复行时的 case 语句

SQL case statement when duplicate rows

目标: col: id 必须是唯一的,不能重复

问题:id_catelog1 为 null 时,id_catelog2 启动但生成多行,因为其中一些有多个 id_catelog2

对于多个,我需要将“多个”放在 id_catelog_final 而不是 id_catelog2 下。

到目前为止,这是我的查询:

select distinct
    id,
    name,
    id_catelog1,
    Large_id_catelog2,
    case 
        when id_catelog1 is null 
            then id_catelog2 
            else id_catelog1 
    end as id_catelog_final
from
    table
where 
    id is not null;

我认为您需要使用条件逻辑进行聚合:

select id, name,
       (case when max(coalesce(id_catelog1, Large_id_catelog2)) =
                  min(coalesce(id_catelog1, Large_id_catelog2))
             then min(coalesce(id_catelog1, Large_id_catelog2))
             else 'multiple'
         end)                  
from t
group by id, name