SQL Server 2014 Word Count

前端 未结 4 1493
温柔的废话
温柔的废话 2021-01-07 14:17

I have a SQL Server database that I\'m searching for keywords.

All I need to know is how many of the keywords appear in a column.

For example



        
相关标签:
4条回答
  • 2021-01-07 14:51

    Try this one

    WITH C(txt) AS(
      SELECT 'I like red shoes but not blue'
      UNION
      SELECT 'I like red shoes and green shoes, but green are my favourite'
    )
    SELECT COUNT(txt)
    FROM C WHERE txt LIKE '%green%'
    OR txt LIKE '%blue%'
    OR txt LIKE '%red%'
    
    0 讨论(0)
  • 2021-01-07 15:09

    You can use a string splitter for this. Here is the DelimitedSplit8K function by Jeff Moden.

    DECLARE @str VARCHAR(8000) = 'I like red shoes and green shoes, but green are my favourite'
    
    SELECT
        COUNT(DISTINCT ITEM)
    FROM dbo.DelimitedSplit8K(@str, ' ')
    WHERE
        Item IN('red', 'green', 'blue')
    

    SQL Fiddle

    0 讨论(0)
  • 2021-01-07 15:09

    This will work

         create table #temp(color varchar(500))
    insert into #temp(color) values('red')
    insert into #temp(color) values('green')
    insert into #temp(color) values('blue')
    
    Create table #temp2(string varchar(max))
    insert into #temp2(string) values('I like red shoes and green shoes, but green are my favourite')
    insert into #temp2(string) values('I like red shoes and green shoes')
    
    select string,count(*) from #temp inner join #temp2 on PATINDEX('%'+color+'%',string)>0
    group by string
    
    0 讨论(0)
  • 2021-01-07 15:14

    Try this

    SELECT b.LineText, count(*) from 
    FROM
    (
    select 'RED' Colors
    union
    select 'GREEN'
    union
    select 'BLUE'
    ) a
    JOIN
    (
    SELECT 'I like red shoes but not blue' LineText
    UNION
    SELECT 'I like red shoes and green shoes, but green are my favourite'
    ) b ON b.LineText LIKE '%'+a.Colors+'%'
    group by b.LineText
    
    0 讨论(0)
提交回复
热议问题