So I have thousands of records in a database in a column A.
I want to see how many start with each letter of the alphabet and all single digit numbers.
So i need
You can generally GROUP BY
an expression like LEFT(columnname, 1)
, which allows you to perform a COUNT()
aggregate grouped by an arbitrary expression. The most ideal substring function to use may depend on your RDBMS.
SELECT
UPPER(LEFT(columnname, 1)) AS first_char,
COUNT(*)
FROM yourtable
GROUP BY UPPER(LEFT(columnname, 1))
ORDER BY first_char ASC
Likewise, to get the 2 character match
SELECT
UPPER(LEFT(columnname, 2)) AS first_2char,
COUNT(*)
FROM yourtable
GROUP BY UPPER(LEFT(columnname, 2))
ORDER BY first_2char ASC
Some RDBMS will allow you to use the column alias in the GROUP BY
rather than the full expression, as in the simplified GROUP BY first_char
.
Note that I have upper-cased them so you don't get separate matches for Ab, AB, ab, aB
if you are using a case-sensitive collation. (I believe SQL Server uses case-insensitive collations by default, however)