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

avkwfej4  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(263)

在sql查询中,我有一列要用作模型的响应。
它可以包含x个类别;

Variable
-------

ProductA, ProductB

ProductC, ProductZ, ProductB

ProductA, ProductC

ProductA

我想把它转换成一个响应变量,最好的方法是什么,我怎么做?
例如(对于第一栏)这样的东西对推荐人来说有意义吗?

Product A | Product B | Product C

1  |  1  | 0
nbysray5

nbysray51#

如果我理解正确,您可以使用 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' .

相关问题