mysql - 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 中实现吗?如果可能的话,请解释我如何。
提前致谢。
解决方案
您可以在用 '' 替换 '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
推荐阅读
- android - 颤振应用程序未运行 - 找不到 aapt2-windows.jar
- java - 找不到约束的验证器
- nonlinear-optimization - 优化,使用 Quantlib 和 Scipy 差分进化,不收敛
- python - Python - 从 ASPX 页面下载 PDF
- mysql - TIME 类型字段中的 GROUP BY - MySQL
- python - 如何在离线使用的 Kivy 应用程序中显示 openstreetmap 切片?
- javascript - 页面加载时在 Select2 上设置所选项目 (ASPX)
- python - 在python中强制输入
- typescript - 为什么在类中调用映射类型会触发编译错误
- gitlab - Gitlab 和外部 SSO