使用case创建一个新列MySQL



我是SQL新手,我正在尝试使用另一列的值创建一个新列。

我用的是这样的。

Select 
a.idclientecrm,
(case
when a.titulo like '%Mensual'       then 'Mensual'
when a.titulo like '%Trimestral'    then 'Trimestral'
when a.titulo like '%Semestral'     then 'Semestral'
when a.titulo like '%Anual'         then 'Anual'
else null
end) as Periodo_Producto
from tareas a

当我在a中找到 menu 这个词时。titulo我需要单词' menu '在新列等每个不同的时间段( trimestal semestal annual )。

"喜欢"部分似乎不起作用,我也尝试了包含,但我也不能使它工作。

希望大家能理解

%置于String的两端

   Select 
    a.idclientecrm,
    (case
    when a.titulo like '%Mensual%'       then 'Mensual'
    when a.titulo like '%Trimestral%'    then 'Trimestral'
    when a.titulo like '%Semestral%'     then 'Semestral'
    when a.titulo like '%Anual%'         then 'Anual'
    else null
    end) as Periodo_Producto
    from tareas a

您需要在比较字符串的末尾(以及开始处)添加一个'%'符号,以便比较检查字符串中的任何地方-目前它只检查字符串是否以时间段单词结束。试一试:

Select 
a.idclientecrm,
(case
when a.titulo like '%Mensual%'       then 'Mensual'
when a.titulo like '%Trimestral%'    then 'Trimestral'
when a.titulo like '%Semestral%'     then 'Semestral'
when a.titulo like '%Anual%'         then 'Anual'
end) as Periodo_Producto
from tareas a

(另外,else null是不必要的-默认情况下,case在没有匹配条件的情况下返回null)

在两端使用%

Try this:

Select 
a.idclientecrm,
(case
when a.titulo like '%Mensual%'       then 'Mensual'
when a.titulo like '%Trimestral%'    then 'Trimestral'
when a.titulo like '%Semestral%'     then 'Semestral'
when a.titulo like '%Anual%'         then 'Anual'
else null
end) as Periodo_Producto
from tareas a

给你一把小提琴。

希望这是根据您的需要。谢谢!

最新更新