首页 > 解决方案 > 根据其他列中存在的数据修改列的内容

问题描述

我拥有的数据如下所示 -

category_id  category  Type_1    Type_2    no_of_items
   123         cat_A      A       both         5
   123         cat_A      B       both         10
   123         cat_B      B       both         35
   123         cat_B      A       both         10
   123         cat_C      A       both         20

我想达到以下结果-

当 category_id 时,category 为 SAME,Type_2 为“both”(Type_2 中还有很多其他类型)-

检查 Type_1 是否有 A 和 B 的记录,如果有,则将 Type_1 更改为“两者”,否则保持原样并将no_of_items 相加。

如果 Type_1 有 A 或 B 的记录,则保持 Type_1 原样。

结果应该看起来像 -

category_id  category  Type_1    Type_2    no_of_items
   123        cat_A    both       both         15
   123        cat_B    both       both         45
   123        cat_C      A        both         20

标签: sqlgroup-bygoogle-bigquery

解决方案


如果我让你正确,那么下面的查询将通过sum(no_of_items). 这是 postgres 中的演示,但同样的解决方案应该适用于 BigQuery。

select
    category_id,
    category,
    case when total = 2 then 'both' else Type_1 end as Type_1,
    Type_2,
    sum(no_of_items) as no_of_items
from
(select
    category_id,
    category,
    Type_1,
    Type_2,
    no_of_items,
    count(Type_1) over (partition by category) as total
from category
) t
group by
    category_id,
    category,
    case when total = 2 then 'both' else Type_1 end,
    Type_2
order by
    category

输出:

----------------------------------------------------
category_id category    type_1  type_2  no_of_items
----------------------------------------------------
    123     cat_A         both   both     15
    123     cat_B         both   both     45

推荐阅读