最后4个字符分组,并显示组

时间:2015-02-10 22:32:12

标签: mysql sql select group-by

lastname表格中有一列mytable varchar(50)。

我会在最后 4个字母上拆分组lastname列并计算这些组。

这样做的方法是什么?

刚添加: 这是对的吗?

select substr(lastname,-4) as alpha, count(lastname)
  from mytable
 group by substr(lastname,-4)

新更新:

select right(lastname,4) as alpha, count(lastname) as total
  from orig
 group by alpha
 order by total desc;

1 个答案:

答案 0 :(得分:1)

不知道MySQL是否支持在组中通过以下方式非标准地使用列别名:

select right(lastname,4) as alpha,
       count(lastname) as total
from orig
group by alpha
order by total desc;

或者,或许:

select alpha, count(*) as total
from (select right(lastname,4) as alpha from orig)
group by alpha
order by total desc;