I have the following tables:
Material
material_ID | material_Name
A | Sugar
B | Flour
C | Egg Yolk
D | Water
E | Tea Powder
Product
product_ID | product_Name | material_ID
1 | Cake | A
1 | Cake | B
1 | Cake | C
2 | Tea | D
2 | Tea | E
2 | Tea | A
ScaleData
record_ID | product_ID | material_ID | Weight
1001 | 1 | A | 30
1002 | 1 | B | 11
1003 | 1 | C | 25
1004 | 1 | A | 31
1005 | 1 | B | 25
1006 | 2 | D | 15
1007 | 2 | E | 20
1008 | 2 | E | 21
As you can see: product no 1 is cake and it require material: A, B, and C in order to form a complete product. Product no 2 is tea and it require material: D, E, and A to form a complete product.
From the weighing table (ScaleData) we can see that there is 1 cake and 0 tea.
record_ID: 1001, 1002, 1003 creates one complete cake.
record_ID: 1004, 1005 are remaining incomplete cake ingredients.
record_ID: 1006, 1007, 1008 are remaining incomplete tea ingredients.
Question:
A. How can i create the following result table based on data from above tables:
Result
product_ID | product_Name | Qty
1 | Cake | 1
2 | Tea | 0
B. How can i display the remaining ingredients like below?
Remaining
record_ID | product_ID | material_ID | Weight
1004 | 1 | A | 31
1005 | 1 | B | 25
1006 | 2 | D | 15
1007 | 2 | E | 20
1008 | 2 | E | 21
EDIT: I am currently able to solve this with a mix of .NET Code + SQL Query. What I am looking for is pure SQL Query solution. My current method is as follows:
1. Execute: "SELECT DISTINCT product_ID FROM Product" to get a list of Product_ID.
2. Iterate through each product_ID and retrieve list of material from each product.
Something like: "SELECT material_ID FROM Product WHERE product_ID=1"
3. Scan ScaleData table for each material and get the total row counts
Something like:
TotalA = "SELECT COUNT(*) FROM ScaleData WHERE product_ID=1 AND material_ID='A'
TotalB = "SELECT COUNT(*) FROM ScaleData WHERE product_ID=1 AND material_ID='B'
TotalC = "SELECT COUNT(*) FROM ScaleData WHERE product_ID=1 AND material_ID='C'
4. Compare variables: TotalA, TotalB, TotalC and get the lowest value.
Lets say TotalA = 2 ; TotalB = 2 ; TotalC = 1
LowestCount = TotalC = 1
5. Then we can tell total Qty for product 1 is 1 ( based on lowest count ).
Remaining for Material A = 2 - 1 = 1
Remaining for Material B = 2 - 1 = 1
That is my current solution and I know it is not very efficient. I prefer pure SQL solution and I hope some SQL Gurus are willing to help me..
This would do the first part. It could probably be cleaned up, but what it basically does is to take the ingredient there is least of per product, and that’ll be the number of products you can make.
I made an SQLfiddle to test with for anyone with time to write the second part 😉