How do I count individual text count from a column from all records [duplicate]

核能气质少年 提交于 2019-12-08 04:24:19

If you are using versions other than SQL SERVER 2016, you need to create an User defined function to split these comma separated strings.

The whole answer is as follows:

Go

CREATE FUNCTION [dbo].StringSplit
(
    @Labels varchar(8000)
)
RETURNS @RESULT TABLE(Value VARCHAR(8000))
AS
BEGIN     
 DECLARE @SeparatorPosition INT = CHARINDEX(',', @Labels ),
        @Value VARCHAR(8000), @StartPosition INT = 1

 IF @SeparatorPosition = 0  
  BEGIN
   INSERT INTO @RESULT VALUES(@Labels)
   RETURN
  END

 SET @Labels = @Labels + ','
 WHILE @SeparatorPosition > 0
  BEGIN
   SET @Value = SUBSTRING(@Labels , @StartPosition, @SeparatorPosition- @StartPosition)

   IF( @Value <> ''  ) 
    INSERT INTO @RESULT VALUES(@Value)

   SET @StartPosition = @SeparatorPosition + 1
   SET @SeparatorPosition = CHARINDEX(',', @Labels , @StartPosition)
  END    

 RETURN
END
Go

After creating the above function, following query should get the job done:

select concat(fn.Value,'(',count(fn.Value),')') as TagCount 
from addnew a
 cross apply
   STRINGSPLIT(a.Labels) as fn
 group by fn.Value
 order by TagCount;

Working Example

Note: If you are using Sql Server 2016, then you can use in-built function STRING_SPLIT().

For more info click here

Solution for SQL SERVER 2016:

select concat(fn.Value,'(',count(fn.Value),')') as TagCount 
    from addnew a
     cross apply
       STRING_SPLIT(a.Labels) as fn  //use in-built function, no need to create UDF
     group by fn.Value
     order by TagCount;

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!