这是我的表:
----------+-----------+--------------
45678-sm-w| 18 | Mens clothing
----------+-----------+--------------
45678-sm-b| 5 | Mens clothing
----------+-----------+--------------
2189-L-Wh | 4 | Juniors Clothing
----------+-----------+--------------
2189-L-Bl | 3 | Juniors Clothing
----------+---------- +--------------
这就是期望的结果:
----------+-----------+--------------
45678 | 23 | Mens clothing
----------+-----------+--------------
2189 | 7 | Juniors Clothing
----------+-----------+--------------
答案 0 :(得分:5)
如果您正在选择数据,那么您可以使用以下内容:
select SUBSTRING_INDEX(col1, '-', 1) col1,
sum(col2) Total,
col3
from table1
group by SUBSTRING_INDEX(col1, '-', 1), SUBSTRING_INDEX(col3, ' ', 1)
order by col1 desc
答案 1 :(得分:3)
col1
拆分为三列(例如id
,size
和color
)来更改表格是最有意义的,这样您就可以按新id
列:
-----+----+----+-----------+--------------
45678| sm | w | 18 | Mens clothing
-----+----+----+-----------+--------------
45678| sm | b | 5 | Mens clothing
-----+----+----+-----------+--------------
2189 | L | Wh | 4 | Juniors Clothing
-----+----+----+-----------+--------------
2189 | L | Bl | 3 | Juniors Clothing
-----+----+----+---------- +--------------
您可以使用ALTER TABLE
添加所需的三个列并更改主键,使用SUBSTRING_INDEX
和UPDATE
提取并存储拆分值,另一个{{} {1}}进行清理。像这样:
ALTER TABLE
如果您无法更改表格,可以使用SUBSTRING_INDEX提取所需的ID编号:
ALTER TABLE t
DROP PRIMARY KEY;
ALTER TABLE T
ADD id INT UNSIGNED NOT NULL,
ADD size VARCHAR(255),
ADD color VARCHAR(255),
ADD PRIMARY KEY (col1);
UPDATE TABLE t
SET id = CONVERT(SUBSTRING_INDEX(col1, '-', 1), UNSIGNED INTEGER),
SET size = SUBSTRING_INDEX(col1, '-', 2),
SET color = SUBSTRING_INDEX(col1, '-', 3);
ALTER TABLE t
DROP COLUMN col1;
给出:
SELECT SUBSTRING_INDEX(col1, '-', 1), col2, col3 FROM table;
对于最终查询,我会使用一个-----+-----------+--------------
45678| 18 | Mens clothing
-----+-----------+--------------
45678| 5 | Mens clothing
-----+-----------+--------------
2189 | 4 | Juniors Clothing
-----+-----------+--------------
2189 | 3 | Juniors Clothing
-----+---------- +--------------
来提取您需要的ID,并使用外部SELECT
进行分组:
SELECT
答案 2 :(得分:0)
将第一列CAST为数字,为新创建的列添加索引,并在该列上按总和运行组。
update table set `left`=CAST(col1 AS SIGNED );
select `left`,sum(*),`col3` from table;