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.
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;
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