你能改变桌子吗?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
andUPDATE
提取和存储拆分值以及另一个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