how to count rows by first letter?

前端 未结 3 513
暗喜
暗喜 2021-01-14 17:21

a noob question here!

I wrote this query, but the \"group by\" is very stupid... so, how can I correct this?

SELECT
    COUNT(*) AS total,
    \'x\'         


        
相关标签:
3条回答
  • 2021-01-14 17:45

    This should perform as well as any other option -

    SELECT
        LEFT(name, 1) AS first_letter,
        COUNT(*) AS total
    FROM contents
    GROUP BY first_letter
    

    If you want to run this query for a single letter at a time you can add the WHERE clause and drop the GROUP BY -

    SELECT COUNT(*) AS total
    FROM contents
    WHERE name LIKE 'a%'
    
    0 讨论(0)
  • 2021-01-14 17:57

    Let's dissect your query:

    SELECT
        COUNT(*) AS total,
        'x' as test     <-- Why?
        FROM            <-- Bad formatting.
    contents
        WHERE name LIKE 'C%'
    GROUP BY
        test            <-- Removing 'x' and the whole GROUP BY has the same effect.
    ORDER BY id ASC     <-- The result only contains one row - nothing to sort.
    

    So the query that returns one row with one field, containing the number of rows whose name begins with 'C' would look like this:

    SELECT COUNT(*)
    FROM contents
    WHERE name LIKE 'C%'
    

    Having an index whose leading edge is name would ensure good performance. To understand why, take a look at the Anatomy of an SQL Index.

    0 讨论(0)
  • 2021-01-14 17:57

    should give you everything in case you want it

    SELECT
      COUNT(*) AS total,
      test
    FROM
     (SELECT substring(name,1,1) as test
     from contents) t
    GROUP BY test
    
    0 讨论(0)
提交回复
热议问题