首页 > 解决方案 > MySql:根据条件在特定列中显示值

问题描述

我有一个场景,我需要根据条件在特定列中显示一个值。详细地说,我有一个从某个列中获得的值,该列的值包含字符串“a beautiful day”。我有四列;columnA,columnB,columnC,columnD 其中我需要根据条件仅在四列之一中显示此值。

假设这个值“美好的一天”包含等于或多于 3'a,那么我需要将其显示在 columnA 中,其余列应该为空。如果它包含 2 个“a”,我需要将其显示在 columnB 中,如果有 1 个“a”columnC,如果没有“a”,则类似于 columnD。

它应该是这样的:

+-------------------+-------------------+-----------+-----------+-----------+
| stringValue       | columnA           | columnB   | columnC   | columnD   |
+-------------------+-------------------+-----------+-----------+-----------+
| a beautiful day   |a beautiful day    |           |           |           |
| Chelsea F C       |                   |           |Chelsea F C|           |
+-------------------+-------------------+-----------+-----------+-----------+

这可以在 MySql 中实现吗?如果可能的话,请解释我如何。

提前致谢。

标签: mysql

解决方案


您可以在用 '' 替换 'a' 之前和之后检查长度

select case when (length(stringValue ) - length(replace(stringValue, 'a',''))) >= 3 
           then stringValue else null end columnA
    ,  case when (length(stringValue ) - length(replace(stringValue, 'a','')))= 2 
           then stringValue else null end columnB
    , case when (length(stringValue ) - length(replace(stringValue, 'a',''))) = 1 
           then stringValue else null end columnC
    , case when (length(stringValue ) - length(replace(stringValue, 'a',''))) = 0
           then stringValue else null end columnD
FROM my_table 

推荐阅读