Link to home
Start Free TrialLog in
Avatar of holemania
holemania

asked on

SQL Running Value Multiplication

So I have a multi-level BOM in which I am able get all my results.  However, I am struggling to get my calculation.  I am to find all purchased materials that make up the fabricated item.  I had put this into my temp table, but I need to calculate and only output my purchased material and total usage.

User generated image
So with the above temp table, I have 2 fabricated material A1 and G1.  Parent ID A1 consist of B2, C2, and D2 which are all fabricated parts as well.  Each of those components required a purchased material to make.  So I have my level on how deep it is.  Then  you can link the Component ID to the Item ID and it'll take you to the last purchased material.  My issue is the calculation.  Example look at purchased material "F3".  This require .004 to make B2.  B2 require 2 in A1.  In total I should have .008.  However, with my query I am not getting this result.

Here's my expected result.
User generated image
Not sure if I am not doing something right with my query.

DECLARE @TEMP TABLE(
		ITEM_ID VARCHAR(30),
		COMPONENT_ID VARCHAR(30),
		QTY DECIMAL(8,4),
		FAB_PURC VARCHAR(10),
		PARENT_ID VARCHAR(30),
		LVL INT
		);

INSERT INTO @TEMP
VALUES(NULL, NULL, 1, 'FAB', 'A1', 0),
('A1', 'B2', 2, 'FAB', 'A1', 1),
('A1', 'C2', 1, 'FAB', 'A1', 1),
('A1', 'D2', 1, 'FAB', 'A1', 1),
('B2', 'F3', .004, 'PURC', 'A1', 2),
('C2', 'E3', .1324, 'PURC', 'A1', 2),
('D2', 'E3', .0765, 'PURC', 'A1', 2),
(NULL, 'G1', 1, 'FAB', 'G1', 0),
('G1', 'H2', 4, 'FAB', 'G1', 1),
('G1', 'I2', 2, 'FAB', 'G1', 1),
('G1', 'J2', 2, 'FAB', 'G1', 1),
('G1', 'K2', 2, 'FAB', 'G1', 1),
('H2', 'M3', .0394, 'PURC', 'A1', 2),
('I2', 'M3', .03, 'PURC', 'A1', 2),
('J2', 'M3', .027, 'PURC', 'A1', 2),
('K2', 'M3', .0013, 'PURC', 'A1', 2)

SELECT	T.ITEM_ID, T.COMPONENT_ID, T.QTY, T.FAB_PURC, T.PARENT_ID, T.LVL, RT.RUNNING_VALUE
FROM	@TEMP T
		CROSS APPLY
		(
		SELECT	EXP(SUM(LOG(T2.QTY))) RUNNING_VALUE
		FROM	@TEMP T2
		WHERE	T2.PARENT_ID = T.PARENT_ID
				AND T2.COMPONENT_ID <= T.COMPONENT_ID
		) RT

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of holemania
holemania

ASKER

Awesome.  Thank you so much.