-1

We have a table like the following:

|  SKU    | Manufacturer | Qty
|-----------------------------|
|  12345  | GE, Sony     | 10
|  123456 | GE           | 25

We need to split the rows where more than one manufacturer is listed, and copy the remaining row data (SKU is not unique). So the expected results would be following:

|  SKU    | Manufacturer | Qty
|-----------------------------|
|  12345  | GE           | 10 |
|  12345  | Sony         | 10 |
|  123456 | GE           | 25 |

Can this be even done with MySQL, if so the how? If not, what would other options be then?

Domas
  • 1,133
  • 4
  • 18
  • 46

1 Answers1

1

Try the answer:

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

Check with SQL Fiddle

DineshDB
  • 5,998
  • 7
  • 33
  • 49