在我的数据库中,我有一个数据列表
名称值
a/b/c 1
a/b/c/d 1
a/b/c/d/e 1
b/b/c 1
b/b/c/d 2
c/c/d 3
c/c/d/e 4
d/d 5
如果我设置最大长度3我想要
a/b/c 3
b/b/c 3
c/c/d 7
d/d 5
我该怎么做?
CREATE TABLE dataTable (
ID BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255),
Value INT
) ENGINE=InnoDB;
INSERT INTO dataTable (Name, Value) VALUES ("a/b/c", 1), ("a/b/c/d", 1), ("a/b/c/d/e", 1), ("b/b/c", 1), ("b/b/c/d", 1), ("c/c/d", 1), ("c/c/d/e", 1), ("d/d", 1);
答案 0 :(得分:2)
SELECT LEFT(Name, 5) AS Name, SUM(Value) as TotalValue
FROM dataTable
GROUP BY LEFT(Name, 5)
显然,我在我的例子中对5进行了硬编码,但你可以做一个像(2 * MaxLen-1)这样的变量。
答案 1 :(得分:1)
select name,
sum(value) as cnt
from
dataTable
group by substring_index(name,'/',3)