简体   繁体   English

SQL计数字符串在每一行中匹配

[英]SQL count string matches in each row

Please take a look at this simple SQL server database : 请看一下这个简单的SQL Server数据库: 数据库

What I want is, I want to create a summary with only 3 column, here is the code: 我想要的是,我想创建一个只有3列的摘要,这是代码:

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

I want the result to have 3 column, and the column "CountString" is the total number of string that matches ('this','is', 'count', 'example'). 我希望结果具有3列,而“ CountString”列是匹配的字符串总数(“ this”,“ is”,“ count”,“ example”)。 Here is the result I want : 这是我想要的结果:

结果

So for example, I want the Countstring for ProductID 1 is 4, because it contains all of 4 words. 例如,我希望ProductID 1的Countstring为4,因为它包含所有4个单词。

If you can solve this, it would be amazing! 如果您能解决这个问题,那就太好了!

If I understand correctly: 如果我正确理解:

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;

Note: Any Name that has "this" also has "is". 注意:任何具有“ this”的Name也将具有“ is”。

If "words" are separated by spaces (and only spaces), you can do: 如果“单词”由空格(仅空格)分隔,则可以执行以下操作:

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;

The following query should suffice your need --- 以下查询足以满足您的需求-

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

This query will result in "Case Sensitive" checking, means only "example" will be counted not "Example". 此查询将导致“区分大小写”检查,这意味着仅“示例”将被计为“示例”。 If you want "Case Insensitive" checking just put 'i' instead of 'c'. 如果要“不区分大小写”检查,只需输入“ i”而不是“ c”。

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

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