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

爱⌒轻易说出口 提交于 2019-12-23 03:28:21

问题


I need to display count of each text occurrence on all rows from a particular column.

See result below:

Here I have a set of Tags, I need to display count each tag as column in the name 'Total'

What I have done is:

DECLARE @tags VARCHAR(8000) 
DECLARE @tot INT
select @tags = coalesce(@tags + ',' , ' ') + Labels from addNew 
select @tot = count(@tags)
select a.Labels as Tags,@tot as Total from addNew a 
inner join addNew n
on a.Labels = n.Labels
group by a.Labels

The result must be:


Get the query code: individual_count_set.sql
Please suggest your queries to get my desired result.

Thank in Advance.


回答1:


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!



来源:https://stackoverflow.com/questions/46593133/how-do-i-count-individual-text-count-from-a-column-from-all-records

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