1

这是我的桌子:

----------+-----------+--------------
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
----------+-----------+--------------
4

3 回答 3

7

如果您正在选择数据,那么您可以使用以下内容:

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

请参阅带有演示的 SQL Fiddle

于 2012-10-12T19:10:14.603 回答
4

你能改变桌子吗?col1通过拆分为三列(例如idsize和)来更改表是最有意义的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_INDEXandUPDATE提取和存储拆分值以及另一个ALTER TABLE用于清理来完成此操作。像这样的东西:

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;

如果您无法更改表,则可以使用SUBSTRING_INDEX提取所需的 id 号:

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
-----+---------- +--------------

对于最终查询,我将使用一个SELECT来提取您需要的 id,并使用一个外部SELECT来进行分组:

SELECT id, SUM(col2) AS total, col3
FROM 
    (SELECT SUBSTRING_INDEX(col1, '-', 1) AS id, col2, col3
    FROM table) AS t
GROUP BY id
于 2012-10-12T19:22:37.327 回答
0

将第一列转换为数字,将索引添加到新创建的列,并在该列上按总和运行一个组。

update table set `left`=CAST(col1 AS SIGNED );

select `left`,sum(*),`col3` from table;
于 2012-10-12T19:03:54.673 回答