【问题标题】:SQL count string matches in each row每行中的 SQL 计数字符串匹配项
【发布时间】:2017-08-23 12:01:07
【问题描述】:

请看一下这个简单的 SQL 服务器数据库:

我想要的是,我想创建一个只有 3 列的摘要,这里是代码:

select ProductID, Name,
       *code* as CountString
from product
where Name in ('this', 'is', 'count', 'example')

我希望结果有 3 列,“CountString”列是匹配的字符串总数('this'、'is'、'count'、'example')。这是我想要的结果:

例如,我希望 ProductID 1 的 Countstring 为 4,因为它包含所有 4 个单词。

如果你能解决这个问题,那就太棒了!

【问题讨论】:

  • 用您正在使用的数据库标记问题。还可以编辑问题并显示您想要的结果。
  • 完成!给你
  • @RaspiSurya 如果一个词出现多次,应该计算多次还是算1?
  • 如果有产品名称“这叫这句话”,应该算5个字。你能解决吗?

标签: sql sql-server count


【解决方案1】:

如果我理解正确:

select ProductID, Name,
       ( (case when Name like '%this%' then 1 else 0 end) +
         (case when Name like '%is%' then 1 else 0 end) +
         (case when Name like '%count%' then 1 else 0 end) +
         (case when Name like '%example%' then 1 else 0 end)
       ) as CountString
from product;

注意:任何有“this”的Name也有“is”。

如果“单词”用空格(且只有空格)分隔,您可以这样做:

select ProductID, Name,
       ( (case when concat(' ', Name, ' ') like '% this %' then 1 else 0 end) +
         (case when concat(' ', Name, ' ') like '% is %' then 1 else 0 end) +
         (case when concat(' ', Name, ' ') like '% count %' then 1 else 0 end) +
         (case when concat(' ', Name, ' ') like '% example %' then 1 else 0 end)
       ) as CountString
from product;

【讨论】:

【解决方案2】:

以下查询应该可以满足您的需要---

SELECT PRODUCTID,
       NAME,
       REGEXP_COUNT(NAME, 'this|is|count|example', 1, 'c') CountString
  FROM product;

此查询将导致“区分大小写”检查,这意味着只计算“示例”而不计算“示例”。如果您想要“不区分大小写”检查,只需输入 'i' 而不是 'c'。

【讨论】:

  • 什么是 REGEXP_COUNT?这是错误:Msg 195, Level 15, State 10, Line 4 'REGEXP_COUNT' is not a recognized built-in function name.
  • REGEXP_COUNT 是 Oracle 内置函数。我认为 SQL Server 需要它。正在寻找替代品。一旦找到就会发布。
  • SQL SERVER 中似乎没有 REGEXP_COUNT 的替代品。所以请坚持 Gordon Linoff 分享的内容。
猜你喜欢
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多