How to return all the characters from a string and count it in sql.
if the string is "how are you"
it should return
char count
2
h 1
o 2
w 1
a 1
r 1
e 1
y 1
u 1
How to return all the characters from a string and count it in sql.
if the string is "how are you"
it should return
char count
2
h 1
o 2
w 1
a 1
r 1
e 1
y 1
u 1
You can use this script. It will give you exactly what you need. This one counts just the letters in the string.
declare @c int
declare @ch varchar(10)
declare @str varchar(max)
set @str = 'how are you'
declare @letter int
declare @i int
set @i = 1
create table #tbl(ch varchar(10), cnt int)
while (@i <= len(@str))
begin
set @letter = 0
set @ch = substring(@str, @i, 1)
select @c = count(*) from #tbl
where ch = @ch
if ( (@ch >= 'a' and @ch <= 'z') or (@ch >= 'A' and @ch <= 'Z') )
begin
set @letter = 1
end
if (@c = 0)
begin
if (@letter = 1)
begin
insert into #tbl (ch, cnt) values (@ch, 1)
end
end
else
begin
update #tbl set cnt = cnt + 1 where ch = @ch
end
set @i = @i + 1
end
select * from #tbl
drop table #tbl
And if you want to count all chars (not just letters), this makes it even easier. Use this script.
declare @c int
declare @ch varchar(10)
declare @str varchar(max)
set @str = 'how are you'
declare @i int
set @i = 1
create table #tbl(ch varchar(10), cnt int)
while (@i <= len(@str))
begin
set @ch = substring(@str, @i, 1)
select @c = count(*) from #tbl
where ch = @ch
if (@c = 0)
begin
insert into #tbl (ch, cnt) values (@ch, 1)
end
else
begin
update #tbl set cnt = cnt + 1 where ch = @ch
end
set @i = @i + 1
end
select * from #tbl
drop table #tbl
You can use a customer tsql function, see http://gallery.technet.microsoft.com/scriptcenter/T-SQL-Script-to-Split-a-308206f3.
And you can make a query solve your issue using group by
and count
statements ?
This will return the result set you have requested. It does this by taking each letter and adding it to a new row within a temporary table and then querying the results to return the counts for each occurrence of the character.
DECLARE @individual CHAR(1);
DECLARE @text NVARCHAR(200)
SET @text = 'how are you';
IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL
DROP TABLE #tmpTable
CREATE TABLE #tmpTable (letter char(1));
WHILE LEN(@text) > 0
BEGIN
SET @individual = SUBSTRING(@text, 1, 2)
INSERT INTO #tmpTable (letter) VALUES (@individual);
SET @text = SUBSTRING(@text, 2, LEN(@text))
END
SELECT letter, COUNT(*) AS [count]
FROM #tmpTable
GROUP BY letter;