MySQL is still pretty new to me, so I’m having difficutly finding the answer to this particular problem.
I have roughly 60 vendor tables that I would like to join into one table. Alot of our vendors carry the same items so I would like to add all of the items to one table, and those that have the same sku, add the quantities together. I would also like to insert the greater cost and price, and round it up to .99, but if it gets too complicated or can’t be sone, I will stick with just the sku’s and quanitity for now. I would like to start with 2 tables until I can figure it out, then once I grasp the solution I can work on all of them. Here’s an example of 2 tables:
Table A (SKU will be the primary key)
SKU Vendor A SKU Cost Price QTY
1000 VA100 49.99 62.99 10
1001 VA101 64.44 81.99 6
1002 VA102 37.67 47.99 24
1003 VA103 28.33 35.99 16
1004 VA104 26.33 35.99 18
Table B (SKU will be the primary key)
SKU Vendor B SKU Cost Price QTY
1000 VB100 49.99 62.95 21
1001 VB101 64.44 81.95 16
5001 VB501 32.67 40.95 4
5002 VB502 88.44 110.95 12
5003 VB503 87.21 109.95 2
So the End Result will look like this
SKU Vendor A SKU Vendor B SKU Cost Price QTY
1000 VA100 VB100 49.99 62.99 31 <-- Sum
1001 VA101 VB101 64.44 81.99 22 <-- Sum
1002 VA102 37.67 47.99 24
1003 VA103 28.33 35.99 16
1004 VA104 26.33 35.99 18
5001 VB501 32.67 40.95 4
5002 VB502 88.44 110.95 12
5003 VB503 87.21 109.95 2
As you can see the first 2 had the quantities added together, as well as the greater of cost and price inserted. I’ve tried variations of:
Create Table MASTER
SELECT TableA.sku,TableA.VendorA_sku,TableA.cost,TableA.price,TableA.qty
UNION ALL
SELECT TableB.sku,TableB.VendorB_sku,TableB.cost,TableB.price,TableB.qty
GROUP BY sku
And variations of:
Create Table MASTER
AS SELECT TableA.sku,TableA.VendorA_sku,TableA.cost,TableA.price,SUM(TableA.qty+TableB.qty)
GROUP BY sku
I’ve tried numerous different types of Joins and unions and can’t seem to get anything to look the way I need it to, nor have I played around with the adding and rounding of cost and price, as I can’t get past the adding of quanitity in duplicate Primary keys. I have to do this on a daily basis with roughly 60 tables and about 600k sku’s, so any help would be greatly appreciated.
(I also Apologize in advance if I didn’t type this correctly as I’m new to these types of forums)
The following should work for you:
see SQL Fiddle with Demo
A few things to decide, do you want the
AVG()orMAX()cost and price if the values are different or which one do you want to return? If you do then you will use the following to returnMAX():see SQL Fiddle with Demo