i have a list of users in my Postgresql db and i want to count how many users there are for every letter.
Here is the SQL query:
select chr(chars.letter + ascii('A')) as letter,
count(m.nome)
from generate_series(0, 25) as chars(letter)
left join merchant m on ascii(left(m.nome, 1)) = chars.letter + ascii('A')
group by letter
order by letter asc
(thanks to this answer)
Here is the result in PHPPGAdmin:
Now since i migrate to MySQL i need to use the same query but it seems that MySQL doesn't use generate_series(). So, how to get the same result?
So lets assume you have some table with at least 26 records in it (maybe
information_schema.columns
perhaps?).The following will generate all uppercase alphabetical letters:
To embed the above into your original query, put the
SET @c := 64;
before the query, then replacegenerate_series(0, 25) as chars(letter)
with( SELECT CAST ... LIMIT 26 ) chars
. Be sure to include the parentheses as it will make the query into a subquery.SQL Fiddle of the query: http://sqlfiddle.com/#!9/6efac/8
Here is the final solution:
Source