Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and count the values merged with delimiters

Tags:

sql

sql-server

I have a|b|c|d|.. values in a cell. How can I use to count the total occurrence of b in all the calls by splitting it with the help of delimiter

like image 729
Candy Avatar asked Dec 16 '22 11:12

Candy


2 Answers

If you need to count the number of occurances, you can use this (SQL Server):

SELECT LEN(yourColumn) - LEN(REPLACE(yourColumn, 'b', '')) FROM yourTable
like image 112
Alex Avatar answered Jan 30 '23 17:01

Alex


I'm on SQL-Server 2005 and use this Split function:

SELECT split.Item, count=Count(*)
FROM dbo.Foo f
CROSS APPLY dbo.Split(f.ColName, '|')split
GROUP BY split.Item
Having split.Item='b'

Here the table valued function:

CREATE FUNCTION [dbo].[Split]
(
    @ItemList NVARCHAR(MAX), 
    @delimiter CHAR(1)
)
RETURNS @IDTable TABLE (Item VARCHAR(50))  
AS      

BEGIN    
    DECLARE @tempItemList NVARCHAR(MAX)
    SET @tempItemList = @ItemList

    DECLARE @i INT    
    DECLARE @Item NVARCHAR(4000)

    SET @tempItemList = REPLACE (@tempItemList, ' ', '')
    SET @i = CHARINDEX(@delimiter, @tempItemList)

    WHILE (LEN(@tempItemList) > 0)
    BEGIN
        IF @i = 0
            SET @Item = @tempItemList
        ELSE
            SET @Item = LEFT(@tempItemList, @i - 1)
        INSERT INTO @IDTable(Item) VALUES(@Item)
        IF @i = 0
            SET @tempItemList = ''
        ELSE
            SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i)
        SET @i = CHARINDEX(@delimiter, @tempItemList)
    END 
    RETURN
END  

DEMO

like image 36
Tim Schmelter Avatar answered Jan 30 '23 18:01

Tim Schmelter