3

Let's say I have two columns:

Table: MyTable

myString 
----------
 abaa
 abb
 a
 bc     

I'm looking for a query that would return the count of each char within the myString column. In this case, it would return :

letter     count
-----------------
a            5
b            3
c            1

The only way I found to count chars was by a convoluted deletion method (count the length without the char, delete the char, and then recount), so I'm wondering if there would be a way to accomplish this more complicated task.

pomegranate
  • 755
  • 5
  • 19

3 Answers3

3

This will be slow (as will likely any solution in SQL), but you can use a numbers table to split apart the letters and count them:

SELECT
  SUBSTRING(myString, number, 1) AS Letter,
  COUNT(*) AS LetterCount
FROM
  numbers n
  JOIN myTable mt
    ON n.number <= CHAR_LENGTH(mt.myString)
GROUP BY SUBSTRING(myString, number, 1)

Working SQL Fiddle

Community
  • 1
  • 1
Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109
2

You are quite close to the goal. You can achieve this with the following query :

select sum(length(mystring)) - sum(length(replace(mystring, 'a', ''))) as count_a
from mytable
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
0

An alternative solution is using stored procedures.
See the SQL Fiddle.

I really think this isn't the best solution, i don't recommend use this in production with a table that contains a significative length of data.

But, for study or experimental purposes.
Hugs.

Andrey
  • 1,476
  • 1
  • 11
  • 17