我们有一个如下表格:
| SKU | Manufacturer | Qty
|-----------------------------|
| 12345 | GE, Sony | 10
| 123456 | GE | 25
我们需要拆分列出多个制造商的行,并复制剩余的行数据(SKU不是唯一的)。所以预期结果如下:
| SKU | Manufacturer | Qty
|-----------------------------|
| 12345 | GE | 10 |
| 12345 | Sony | 10 |
| 123456 | GE | 25 |
甚至可以用MySQL完成,如果是这样的话怎么样?如果没有,那么其他选择会是什么呢?
答案 0 :(得分:1)
尝试答案:
CREATE TABLE Temp (SKU INT, Manufacturer VARCHAR(15),Qty INT);
INSERT INTO Temp VALUES(12345,'GE, Sony',10);
INSERT INTO Temp VALUES(123456,'GE',25);
select
Temp.SKU,
SUBSTRING_INDEX(SUBSTRING_INDEX(Temp.Manufacturer, ',', numbers.n), ',', -1) Manufacturer,
Temp.Qty
from
(select 1 n union all
select 2 union all select 3 union all
select 4 union all select 5) numbers INNER JOIN Temp
on CHAR_LENGTH(Temp.Manufacturer)
-CHAR_LENGTH(REPLACE(Temp.Manufacturer, ',', ''))>=numbers.n-1
order by
SKU, n