将多个 Case 语句组合成单个输出列

发布于 2025-01-11 10:19:24 字数 604 浏览 1 评论 0原文

我需要通过匹配某些条件将具有 10 个唯一值的 marketing_channel 列重新分类为 15 个不同的组。 我已经通过 case 语句完成了此操作,但输出位于 15 个新列中。

  1. 是否有更优雅的方法来重新分类 marketing_channel,只需添加 1 个额外的列(例如包含所有新的 15 个类的 "marketing_sub_channel" )?
  2. 有没有比创建 15 个案例语句更好的分类方法?正在考虑使用 with 子句,但这也会相当冗长

在此处输入图像描述

输出如下所示,但最终只需添加一个列就可以了: 输入图片此处描述

I need to re-categorise a column marketing_channel with 10 unique values into 15 distinct groups by matching certain criteria.
I've done this via case statements but then the output is in 15 new columns.

  1. Is there a more elegant way to re-class the marketing_channel by simply adding 1 extra column like "marketing_sub_channel" that contains all new 15 classes?
  2. Is there better way to do the classification than by creating 15 case statements? Was thinking a with clause, but that would also be quite lengthy

enter image description here

Output looks like this but ultimately just a single added column would be great:
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘和柠 2025-01-18 10:19:24

是的,您只需稍微更改一下格式即可。删除每行开头的“case”语句,然后将“End”放在语句末尾,如下所示:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE null
END as marketing_sub_channel

或者在您的情况下:

CASE
    WHEN medium like ('%affiliate%') or marketing_cannel ='Affiliates' then 'Affiliate'
    WHEN campaign like ('%_Display brand_global Progromatic Display%') then 'Dispay' 
    WHEN campaign like ('%display%') and campaign not like ('progrommatic') then 'Dispay'
    ....
    else null
END as marketing_sub_channel

另外我想指出,在您的 case 语句中,因为您有 '% display%' 和 '%_Displaybrand_global Progromatic Display%',您将较长且更具体的一个放在顶部,以便它可以在需要时触发。如果“%display%”位于顶部,那么它将始终首先触发,因为它包含另一个的子字符串。

Yes you just have to change the format a bit. Remove the "case" statement at the beginning of each line and just put the "End" at the end of the statement, like so :

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE null
END as marketing_sub_channel

or in your case:

CASE
    WHEN medium like ('%affiliate%') or marketing_cannel ='Affiliates' then 'Affiliate'
    WHEN campaign like ('%_Display brand_global Progromatic Display%') then 'Dispay' 
    WHEN campaign like ('%display%') and campaign not like ('progrommatic') then 'Dispay'
    ....
    else null
END as marketing_sub_channel

Also I would like to note that in your case statement since you have '%display%' and '%_Display brand_global Progromatic Display%' that you place the longer more specific one on top so it can trigger if it needs to. If '%display%' is on top then it will always trigger first since it contains a substring of the other one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文