如何使用SQL查询或Python转换作为多类别响应变量的字符串



我在SQL查询中有一列要用作模型的响应。

它可以包含x个类别;

Variable
-------
ProductA, ProductB
ProductC, ProductZ, ProductB
ProductA, ProductC
ProductA

我想把它转换成一个响应变量,什么是最好的方法,我该怎么做?

例如(对于第一列(这样的东西对推荐人来说有意义吗?

Product A | Product B | Product C
1  |  1  | 0

如果我理解正确,您可以使用case。在标准SQL中,您将使用:

select (case when ', ' || variable || ', ' like '%, ProductA, %' then 1 else 0 end) as has_productA,
(case when ', ' || variable || ', ' like '%, ProductB, %' then 1 else 0 end) as has_productB,
(case when ', ' || variable || ', ' like '%, ProductC, %' then 1 else 0 end) as has_productC

请注意在产品名称周围使用分隔符。这一点非常重要,因此'ProductA''ProductAB'不匹配。

相关内容

最新更新