【问题标题】:Search for the most occurring value in a string with SQL使用 SQL 搜索字符串中出现次数最多的值
【发布时间】:2019-10-15 18:56:26
【问题描述】:

所以如果你有这样的字符串:

"lorum ipsum testing with some dummy text lorum woop what testing again."

你有一个像这样的数据库表:

ID |   TESTING
---------------
1  |   dummy
2  |   lorum
3  |   trol
4  |   haha

如何仅使用 sql 检查 string 中出现次数最多的值。

所以在这种情况下它会返回:2 | lorum

起初我认为LOCATE() 函数会很有用。我试过例如:

SELECT *, LOCATE(testing, "<<string comes here>>") FROM <table>

这可能吗?如果不是,最好的方法是什么?

【问题讨论】:

  • 我删除了不一致的数据库标签。请仅使用您实际使用的数据库进行标记。
  • 当然@GordonLinoff,我只是还没有为我的项目选择数据库,并且正在考虑其中任何一个。如果我不确定,下次我不会包括它们。谢谢

标签: sql string count sql-order-by


【解决方案1】:

在 Oracle 中,您可以使用 handy regex method REGEXP_COUNT(),从 11g 版本开始提供:

select *
from mytable
order by regexp_count(
    'lorum ipsum testing with some dummy text lorum woop what testing again.',
    '(^|\W)' || testing || '(\W|$)'
) desc
fetch first 1 rows only

Demo on DB Fiddle

身份证 |测试 -: | :------ 2 |劳伦

注意:fetch first 1 rows only 需要 Oracle 12c(在早期版本中,您需要子查询和ROWNUM)。


在 Postgres 中,您可以使用regexp_matches() 为每个搜索词生成一个匹配数组,然后对元素进行计数:

select id, testing, count(m)
from 
    mytable t,
    regexp_matches(
        'lorum ipsum testing with some dummy text lorum woop what testing again.', 
        '\y' || t.testing || '\y',
        'g'
    ) m
group by id, testing
order by count(m)::int desc
limit 1

Demo on DB Fiddle

【讨论】:

    【解决方案2】:

    这很痛苦,但您可以使用like 和一些字符串操作来计算字符串中的匹配数:

    select t.testing,
           (length(v.str) - length(replace(v.str, t.testing, ''))) / length(t.testing) as num_times 
    from (values ('lorum ipsum testing with some dummy text lorum woop what testing again.')
         ) v(str) join
         t
         on str like concat('%', t.testing, '%')
    order by num_times desc
    limit 1;
    

    注意:这是通用的。在 Postgres 中,我会将字符串拆分为单词并进行相等比较。

    【讨论】:

      【解决方案3】:

      使用 Postgres 这很容易:

      select word, count(*)
      from regexp_split_to_table('lorum ipsum testing with some dummy text lorum woop what testing again.', '\s') as x(word)
      group by word
      order by count(*) desc
      

      【讨论】:

        【解决方案4】:

        这是一种利用STRING_SPLIT(&lt;string&gt;,&lt;separator&gt;) 将测试字符串转换为表格的方法(在 Ms-SQL 中实现)。该表可以与字典连接,并且所有匹配项都使用 GROUP BY 和 Count 进行计数。 我调用了字典表DICTIONARY

        SELECT sub.testing, COUNT(sub.testing) FROM 
        (   SELECT d.testing FROM DICTIONARY d
            INNER JOIN ( SELECT value FROM STRING_SPLIT('lorum ipsum testing with some dummy text lorum woop what testing again.', ' ') ) s
            ON d.testing = s.value
        )   sub
        GROUP BY sub.testing
        ORDER BY COUNT(sub.testing) DESC
        

        结果:DICTIONARY 表中的所有匹配值将与计数一起按降序列出

        【讨论】:

          猜你喜欢
          • 2013-05-06
          • 1970-01-01
          • 2013-05-27
          • 1970-01-01
          • 1970-01-01
          • 2011-04-03
          • 2021-03-19
          • 1970-01-01
          相关资源
          最近更新 更多