SQL计数字符串匹配

时间:2017-08-24 09:05:59

标签: sql sql-server

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

database

我希望结果有3列,而列#34; CountString"是匹配的字符串总数('此'''' count','示例')。 我已设法使用此查询检测到这些单词,但它无法检测到多个单词:

dt[, as.list(coef(lm(y~x1+x2))), by = .(grp)]
#   grp (Intercept)         x1         x2
#1:   a   0.2185345 -0.7334866 -0.5986349
#2:   b   0.4499405 -0.5264809  0.1454797

但是,如果productID 1的名称是"这是计算此示例"。我希望它被算作5.你能解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

试试这个

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

结果

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