简体   繁体   English

SQL计数字符串匹配

[英]SQL count string matches

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

数据库

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”)。 I have managed to detect those words using this query, but it can`t detect multiple words : 我已经设法使用此查询检测到这些单词,但是它无法检测到多个单词:

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;

However, if the name for productID 1 is "this is count this example". 但是,如果productID 1的名称为“这是本示例”。 I want it to be counted as 5. Could you solve this ? 我希望将其计为5。您能解决这个问题吗?

Create Table product(productid int, NAME varchar(100))
Insert Into product Values(1,'this is this example')
Insert Into product Values(2,'this is this this count this example')


 SELECT productid,count(*) as CountString
 FROM
 (
     SELECT A.[productid],  
         Split.a.value('.', 'VARCHAR(100)') AS String  
     FROM  (SELECT [productid],  
             CAST ('<M>' + REPLACE([NAME], ' ', '</M><M>') + '</M>' AS XML) AS String  
         FROM  product) AS A 
     CROSS APPLY String.nodes ('/M') AS Split(a)
 ) As Word
 WHERE String in ('this','is','count','example')
 Group by productid

Try this 尝试这个

DECLARE @TableString TABLE(ID INT IDENTITY,String nvarchar(max))
INSERT INTO @TableString(String)
SELECT 'this is count this example' UNION ALL
SELECT 'Bearing Ball' UNION ALL
SELECT 'BB Ball Bearing ' UNION ALL
SELECT 'this is   example'

-- Here the delimeter is space 
SELECT id AS productid, COUNT(stringValue) AS StringValueCount FROM
 (
 SELECT id ,
        Split.a.value('.', 'VARCHAR(1000)') AS stringValue
    FROM (
        SELECT id,CAST('<S>' + REPLACE(String, ' ', '</S><S>') + '</S>' AS XML) AS String
        FROM @TableString
        ) AS A
    CROSS APPLY String.nodes('/S') AS Split(a)
    )Dt

WHERE  dt.stringValue in ('this','is','count','example')
GROUP BY id

Result 结果

productid      StringValueCount
-----------------------------
   1                5
   4                3

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

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