Query to return the number of times a specific value occurs within a string?

后端 未结 2 1924
傲寒
傲寒 2021-01-24 03:28

Alright so I have two tables. Table1 has an reference number column (A), and a second column that has a string of randomness (B). Table2 has only one column with a list of value

相关标签:
2条回答
  • 2021-01-24 03:52

    Split Function

    CREATE FUNCTION [dbo].[udf_Split]
    (
        @RowData nvarchar(2000),
        @SplitOn nvarchar(5)
    )  
    RETURNS @RtnValue table 
    (
        Id int identity(1,1),
        Data nvarchar(100)
    ) 
    AS  
    BEGIN 
        Declare @Cnt int
        Set @Cnt = 1
    
        While (Charindex(@SplitOn,@RowData)>0)
        Begin
            Insert Into @RtnValue (data)
            Select 
                Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
    
            Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
            Set @Cnt = @Cnt + 1
        End
    
        Insert Into @RtnValue (data)
        Select Data = ltrim(rtrim(@RowData))
    
        Return
    END
    

    Your Data

    DECLARE @Table_1 TABLE ([A] INT,[B] VARCHAR(1000)) 
    INSERT INTO @Table_1 VALUES
    (24,'BLUE; KITTEN; WHITE; PINK; SLOPE; GREEN'),
    (51,'GREEN; CLOUDY; WHITE; CHIPS'), 
    (78,'PATRIOTS; PINK; PINK; WHITE'), 
    (22,'WHITE; RED; TREES; AMY; GREEN')
    
    DECLARE @Table_2 TABLE (ColumnName VARCHAR(100))
    INSERT INTO @Table_2 VALUES 
    ('BLUE'),('WHITE'),('PINK'),('BROWN')
    

    Query

    SELECT T2.ColumnName, TotalNums
     FROM 
    (SELECT Data, COUNT(DATA) TotalNums 
    FROM  @Table_1 t  CROSS APPLY (SELECT * FROM [dbo].[udf_Split](t.B, ';'))C
    GROUP BY Data) T1
    RIGHT JOIN @Table_2 T2 
    ON T1.Data = T2.ColumnName
    

    Result Set

    ╔════════════╦═══════════╗
    ║ ColumnName ║ TotalNums ║
    ╠════════════╬═══════════╣
    ║ BLUE       ║ 1         ║
    ║ WHITE      ║ 4         ║
    ║ PINK       ║ 3         ║
    ║ BROWN      ║ NULL      ║
    ╚════════════╩═══════════╝
    
    0 讨论(0)
  • 2021-01-24 04:16

    I played around a bit and came up with this SQL fiddle

    The relevant SELECT query looks like this (requires two table scans though, I'm sure it can be made more efficient):

    select C, sum(dbo.CountOccurancesOfString(B, C)) as number
    from Tbl_1 join Tbl_2 on 1=1
    group by C
    order by number desc
    

    EDIT This is the function I got from this answer:

    CREATE FUNCTION dbo.CountOccurancesOfString
    (
     @searchString nvarchar(max),
     @searchTerm nvarchar(max)
    )
    RETURNS INT
    AS
    BEGIN
     return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm)
    END
    
    0 讨论(0)
提交回复
热议问题