如何在MySQL中对字符串部分进行GROUP BY

时间:2016-04-21 08:18:59

标签: mysql string group-by

编辑:

假设您已获得下表:

id  string         number
1   stuff::a::312  5 
2   stuff:::a::312 6
3   stuff::a::233  2
4   stuff:b::213   1
5   stuff::b::222  1
6   stuff::c       5

以下当然不起作用:

SELECT string, COUNT(*)
FROM tbl
-- WHERE
GROUP BY string;

希望的结果:

string numbers
a      13
b      2
c      5

很抱歉,但请注意,在c之后是::但之前,就像其余的一样

5 个答案:

答案 0 :(得分:2)

如果模式相同,则可以执行

select 
substring_index(string,'::',1) as string_val,
sum(number) as number
from mytable
group by string_val

答案 1 :(得分:0)

你可以使用SUBSTRING_INDEX()这样做:

SELECT string, COUNT(*)
FROM tbl
-- WHERE
GROUP BY SUBSTRING_INDEX(string, '::', 1);

答案 2 :(得分:0)

请尝试以下方法:

select substr(string,1,1)
     , count(*)
  from tbl
 group by 1
     ;

答案 3 :(得分:0)

只需使用substr:

SELECT substr(string,1, 1), COUNT(*)
FROM tbl
-- WHERE
GROUP BY substr(string,1, 1);

或更复杂的SUBSTRING_INDEX:

SELECT SUBSTRING_INDEX(string, '::', 1), COUNT(*)
FROM tbl
-- WHERE
GROUP BY SUBSTRING_INDEX(string, '::', 1);

答案 4 :(得分:0)

select left(string,1),count(*) from table where string is not null group by left(string,1) order by left(string,1) 

我希望这有帮助, LEFT(字符串)只占用最左边的字符