mysql - 使用 Case 语句计算 MYSQL 中子字符串出现的次数

标签 mysql string count substring

我有一个文本字符串,其中包含多个子字符串,我想计算其中的出现次数。我看到了类似问题的解决方案,但我想知道是否可以使用 case 语句或不创建新表来完成此操作。

基本上,我使用的数据聚合/分析工具只接受非常基本的 MySQL 语句。

示例:

Paid Search:CLICK, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:CLICK, Display:IMPRESSION, Display:IMPRESSION, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:IMPRESSION, Display:CLICK

我想提取“Display:Rich_Media”的计数

最佳答案

在这里,您可以通过以下查询来完成此操作:

SET @your_string :=
'Paid Search:CLICK, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:CLICK, Display:IMPRESSION, Display:IMPRESSION, Display:RICH_MEDIA, Display:RICH_MEDIA, Display:IMPRESSION, Display:CLICK';

SELECT
    ROUND(
        (
            LENGTH(@your_string) - LENGTH(
                REPLACE (
                    @your_string,
                    "Display:RICH_MEDIA",
                    ""
                )
            )
        ) / LENGTH("Display:RICH_MEDIA")
    ) AS totalOccurrence;

说明:

  • 字符串的长度 - 所有出现该字符串后的长度 子串替换为空
  • 此减法的结果 = 您替换的字符数 = 子字符串的长度 * 子字符串出现的次数
  • 现在,如果你将结果除以子串的长度,你会 获取出现的次数。

关于mysql - 使用 Case 语句计算 MYSQL 中子字符串出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079623/

相关文章:

javascript - JS 脏话计数器

php - mysql 计数不同并使用 php 获取结果

php - 从 MySQL 解码 JSON

PHP MYSQL PDO -> Fatal Error 23000 eventhough a special procedure is place

php - 如何将循环中的这两个查询转换为单个 JOINed 查询?

java - 检查 2 个不同的相等实例(包含示例)

javascript - 将给定字符串转换为 Json 对象 Javascript

PHP MYSQL 多词搜索

python - 使用python将一个字符串拆分成它的句子

MySQL Grouping 使用 group_concat 然后 Group BY