通过列的第一个字母从MySQL表中选择COUNT

时间:2012-02-17 23:30:17

标签: php mysql count

我要做的是选择一列中的所有首字母,并获得每个字母出现次数的COUNT。到目前为止,我能够得到每个字母的数量,但不知道如何输出字母本身。

查询:SELECT COUNT(SUBSTRING( last_name , 1, 1)) as letter FROM users GROUP BY SUBSTRING( last_name , 1, 1);

输出:

letter
------
0
4
1
5
1
1
13
1
74
2
2
8
1

如何获取数字旁边的字母?

2 个答案:

答案 0 :(得分:4)

这是一种方式:

SELECT SUBSTRING(last_name, 1, 1) as letter, count(*) as total FROM users 
          GROUP BY SUBSTRING(last_name, 1, 1);

答案 1 :(得分:1)

尽可能直截了当;

SELECT 
  SUBSTRING(last_name,1,1) as letter, 
  COUNT(last_name) AS cnt 
  FROM users 
  GROUP BY SUBSTRING(last_name, 1, 1);

现场演示here