SQL how many records start with the same letter

后端 未结 1 1408
抹茶落季
抹茶落季 2021-01-21 17:19

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

相关标签:
1条回答
  • 2021-01-21 17:56

    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)

    0 讨论(0)
提交回复
热议问题