[New to asking questions] I'm trying to split multiple fields by the common delimited " " using SUBSTRING_INDEX and UNION ALL, which I've completed successfully from other stack overflow answers.
In another example I've also managed to INNER-JOIN another table (product_info)
The problem is when bringing the two together. I'm not familiar with the UNIONS (or INNER JOIN for that matter). So achieve the expected results have been difficult.
Some of the fields contain more than 1 item, which I understand is poor management in itself. Where NITM contains the item, the other fields contain the qty and price of each corresponding item delimited by a space.
example of code in table 'salesimport':
ID | NITM | NQTY | SALE_PRICE |
1 | CAP LIGHT CHAIR | 1 1 2 | 2.99 4.99 44.99 |
2 | LIGHT | 2 | 4.99 |
3 | CHAIR | 4 | 44.99 |
example of code in table 'product_info':
ID | PROD_ID | UNIT_COST | SUPPLIER |
25 | CAP | 1.00 | X&Y |
87 | LIGHT | 1.23 | X&Y |
79 | CHAIR | 9.00 | JONES_CO |
Just using the first spit method with SUBSTRING_INDEX and UNION ALL, each item in the order is entered onto a new row, e.g. ID 1, 1, 1, 2, 3 etc.
But when I try to add the following:
INNER JOIN product_info
ON salesimport.NITM = product_info.PROD_ID
The order lines become duplicated again, something similar to the example below, where each item gets every permutation.
ID | ITEM | QTY | PRICE | UNIT_COST | SUPPLIER |
1 | CAP | 1 | 2.99 | 1.00 | X&Y |
1 | CAP | 1 | 2.99 | 1.23 | JONES_CO |
1 | LIGHT | 1 | 4.99 | 1.00 | X&Y |
1 | LIGHT | 1 | 4.99 | 1.23 | JONES_CO |
Here is my working code:
SELECT *,
Substring_index(Substring_index(nitm, ' ', n.digit + 1), ' ', -1)
AS ITEM,
Substring_index(Substring_index(nqty, ' ', n.digit + 1), ' ', -1)
AS QTY,
Substring_index(Substring_index(sale_price, ' ', n.digit + 1), ' ', -1)
AS PRICE,
Format(Substring_index(Substring_index(nqty, ' ', n.digit + 1), ' ', -1)
*
Substring_index(Substring_index(sale_price, ' ', n.digit + 1), ' '
, -1),
2)
AS SUBTOTAL,
FROM salesimport
INNER JOIN (SELECT 0 digit
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4) AS n
ON Length(Replace(nitm, ' ', '')) <= Length(nitm) - n.digit
example of above code:
ID | ITEM | QTY | PRICE |
1 | CAP | 1 | 2.99 |
1 | LIGHT | 1 | 4.99 |
1 | CHAIR | 2 | 44.99 |
2 | LIGHT | 2 | 4.99 |
3 | CHAIR | 4 | 44.99 |
This is how I would like the final output to look:
ID | ITEM | QTY | PRICE | UNIT_COST | SUPPLIER |
1 | CAP | 1 | 2.99 | 1.00 | X&Y |
1 | LIGHT | 1 | 4.99 | 1.23 | X&Y |
1 | CHAIR | 2 | 44.99 | 9.00 | JONES_CO |
2 | LIGHT | 2 | 4.99 | 1.23 | X&Y |
3 | CHAIR | 4 | 44.99 | 9.00 | JONES_CO |
Sorry for any errors in advance