SQL技巧:利用REGEXP_replace完成字段内容计数
背景:有个字段里面可能一项或多项调查数据,字段和期望所得数如下:
title
["戒骄戒躁,宠辱不惊"] #期望得到数字:2
["轻率","躁动","不善言","疏忽","好为人师"] #期望得到数字:5
解决:
1、由于Mysql5.8好像还没有regex_count类型的函数,所以只能另想办法。
2、思路:将不是"的内容去除(替换为空),然后再统计"的个数,再除以2即可。
代码:
select title, REGEXP_replace(title,'[^"]','') title1, LENGTH(REGEXP_replace(title,'[^"]','')) title_count from ( select '["戒骄戒躁,宠辱不惊"]' title union all select '["轻率","躁动","不善言","疏忽","好为人师"]' title ) t1
返回:
title title1 title_count
["戒骄戒躁,宠辱不惊"] "" 2
["轻率","躁动","不善言","疏忽","好为人师"] """""""""" 10
本文来自博客园,作者:xiaoyongdata(微信号:xiaoyongdata),转载请注明原文链接:https://www.cnblogs.com/xiaoyongdata/p/15799509.html