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
If you need to count the number of occurances, you can use this (SQL Server):
SELECT LEN(yourColumn) - LEN(REPLACE(yourColumn, 'b', '')) FROM yourTable
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With