简体   繁体   English

使用案例语句计算MYSQL中的子字符串出现次数

[英]Count Substring Occurences in MYSQL using Case Statement

I have a string of text that contains multiple substrings within that I'd like to count the occurences of. 我有一个包含多个子字符串的文本字符串,我想计算其中的出现次数。 I saw solutions to a similar question, but I'm wondering if this can be done using a case statement or without creating a new table. 我看到了类似问题的解决方案,但我想知道是否可以使用case语句或不创建新表来完成。

Basically, I'm using a data aggregation/analysis tool that only accepts very basic MySQL statements. 基本上,我使用的数据聚合/分析工具仅接受非常基本的MySQL语句。

Sample: 样品:

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

I'd like to extract a count of "Display:Rich_Media" 我想提取一个“ Display:Rich_Media”的计数

Here you can accomplish this by the following query: 在这里,您可以通过以下查询完成此操作:

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;

Explanation: 说明:

  • Length of your string - length after the all the occurerences of the subtring replaced by empty 字符串的长度-所有subtring出现后的长度替换为空
  • The result of this subtraction = number of characters you replaced = length of your subtring * number of occurrences of the subtring 减法的结果=替换的字符数=减法的长度*减法的出现次数
  • Now if you divide the result by the length of the subtring you will get the number of occurrences. 现在,如果将结果除以Subtring的长度,将获得出现的次数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM