i have one SQL table
in which many records, i want to know how many names are in it and how much time one name in it.
Table NameMst
Name
john,smith,alax,rock
smith,alax,sira
john,rock
rock,sira
I want to find how much name are there and count of its.
expected output should be like this
Name Count
john 2
smith 2
alax 2
rock 3
sira 2
help me to resolved it.
SELECT y.Name, count(*) Count
FROM
(VALUES
('john,smith,alax,rock'),
('smith,alax,sira'),
('john,rock'),
('rock,sira')) x(names)
CROSS APPLY
(
SELECT t.c.value('.', 'VARCHAR(2000)') Name
FROM (
SELECT x = CAST('<t>' +
REPLACE(x.names, ',', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c)
) y
GROUP BY y.Name
Result:
Name Count
alax 2
john 2
rock 3
sira 2
smith 2
You can extract the names using a recursive CTE and some string parsing. The rest is just aggregation:
with cte as (
select (case when names like '%,%'
then left(names, charindex(',', names) - 1)
else names
end) as name,
(case when names like '%,%'
then substring(names, charindex(',', names) + 1, len(names))
end) as names
from names
union all
select (case when names like '%,%'
then left(names, charindex(',', names) - 1)
else names
end) as name,
(case when names like '%,%'
then substring(names, charindex(',', names) + 1, len(names))
end)
from cte
where names is not null
)
select name, count(*)
from cte
group by name;
As you have probably figured out, storing comma delimited lists in SQL Server is a bad idea. You should have an association/junction table with one row per name (and other columns describing the list it is in).
DECLARE @table1 TABLE ( id VARCHAR(50) )
DECLARE @table TABLE ( id1 INT,id VARCHAR(50) )
INSERT INTO @table (id1,id) values (1, 'JOHN,rom')
INSERT INTO @table (id1,id) values (2,'Micky,Raju')
INSERT INTO @table (id1,id) values (2,'Micky,Raju')
INSERT INTO @table (id1,id) values (2,'Micky,Raju')
DECLARE @Min INT,@Max INT ,@str1 VARCHAR(100),@str2 VARCHAR(100)
DECLARE @x INT = 0
DECLARE @firstcomma INT = 0
DECLARE @nextcomma INT = 0
SELECT @x = LEN(id) - LEN(REPLACE(id, ',', '')) + 1 from @table -- number of ids in id_list
WHILE @x > 0
BEGIN
SELECT @nextcomma = CASE WHEN CHARINDEX(',', id, @firstcomma + 1) = 0
THEN LEN(id) + 1
ELSE CHARINDEX(',', id, @firstcomma - 1)
END FROM @table
--select @nextcomma
INSERT INTO @table1
SELECT ( SUBSTRING(id, @firstcomma + 1, (@nextcomma - @firstcomma) - 1) ) FROM @table
SELECT @firstcomma = CHARINDEX(',', id, @firstcomma + 1)FROM @table
SET @x = @x - 1
END
SELECT DISTINCT id,COUNT(id)
FROM @table1
GROUP BY id