﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / T-SQL (SS2K8)  / Calculate component percents without a cursor / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Fri, 24 May 2013 10:19:01 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>[quote][b]gcresse (9/6/2011)[/b][hr]ChrisM,This works fantastic with the test data!  Thanks for your efforts.  Now I will see if I can make it work with my actual tables.I had actually thought of using the Quirky Update with a pivot table as you had mentioned so that is still a Plan B option.Thanks, again.[/quote]Thanks for the feedback. The QU method is well worth a try - it's generally about 5 or 6 times faster to run than a rCTE. The rCTE is quicker and easier to code up and test, but once done and the logic is tested and sound, the same logic can be transposed quite easily to a QU.</description><pubDate>Wed, 07 Sep 2011 01:46:06 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Celko,[quote]Do you have Denali or plans to move to it? DB2? Oracle? A stronger SQL product? The reason I ask is that SQL with the [ROW | RANGE] subclause and it makes this sort of thing much easier.[/quote]We're on Sql Server 2008 R2 with no immediate plans to upgrade.[quote]Have you seen my tee shirts? “Viral Marketing does not work! Tell everyone you know!” and “Social skills are overrated, you meathead!” I am adversarial by nature and have a reputation for it. My wife is an ordained Soto Zen priest and she hits people with a stick! But on the other hand, I do not charge my consulting rates in SQL forums :) [/quote]Made me laugh.  Thanks :-D[quote]Will you be my new best friend? [/quote]Sure, why not... ;-)</description><pubDate>Tue, 06 Sep 2011 18:58:32 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>ChrisM,This works fantastic with the test data!  Thanks for your efforts.  Now I will see if I can make it work with my actual tables.I had actually thought of using the Quirky Update with a pivot table as you had mentioned so that is still a Plan B option.Thanks, again.</description><pubDate>Tue, 06 Sep 2011 18:47:40 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>&amp;gt;&amp;gt;  Your insight into the fact that this system was originally written in COBOL and converted to VB/SQL by the COBOL developer is amazing. Were you once beaten up by a gang of COBOL geeks? &amp;lt;&amp;lt; I earn my living cleaning up bad SQL, so I see a lot of COBOL =&amp;gt; &amp;lt;language du jour&amp;gt; =&amp;gt; SQL. And, yes, I was beaten up by COBOL-ers in my youth; I was a FORTRAN II programmer. That is not really so far off; those were the only languages we had in the commercial world. The status fights were like C++ vs C# fights today. Later, I became an Algol programmer on Burroughs 5000 machinery. Totally alien. &amp;gt;&amp;gt; This particular naming convention is required in our system due to a third-party auditing program that uses triggers to write to an audit table whenever a column value is inserted/updated/deleted. If we duplicate column names between tables, that program doesn't record the audit row correctly. &amp;lt;&amp;lt;That is an awful way to do an audit. In fact, it is illegal for some purposes. Triggers do not tell you who viewed the data and HIPAA, Basel II and other standards require it. It is the most expensive way to audit, too. I would use a third party tool that sits like a fence around the entire schema with its own administration and authorizations. AND its own legal staff. Same idea as keeping the log files on a separate disk. But that is another issue.&amp;gt;&amp;gt; Perhaps it is my fault for over-simplifying the sample data. In reality, the "key" columns in these tables are IDENTITY surrogate keys.&amp;lt;&amp;lt;IDENTITY is not any kind of key and certainly not a surrogate. This is by definition. Doesn't anyone read Dr. Codd? What you have is a count of the physical  insertion attempts in one package on one machine based on random hardware events. No validation, no versification. At best, it is a fake record number from a sequential COBOL mag tape file. Not at all RDBMS. &amp;gt;&amp;gt;  I did not create them that way in the sample data because I wanted to control the values to simplify. If "key" is not the correct term to describe a surrogate key, then what is? &amp;lt;&amp;lt;There out to be job tickets or some other real key that tracks each shipment.A surrogate key is generated by the RDBMS engine, but completely hidden from the user. Think of hashing or indexes or other access methods. You still need a relational key. Would you like the exact quote from Dr. Codd? &amp;gt;&amp;gt; Are surrogate keys now out of style? Because before we introduced them, users had to make up their own identifiers and they kept hand-written logs or Excel spreadsheets... some of them probably chiseled the identifiers in stone tablets as a left-over from the old COBOL days. &amp;lt;&amp;lt;Where was the accounting department with shipment numbers and other things that can be validated and verified? Where are industry standards? &amp;gt;&amp;gt; Again, my fault for over-simplifying. In reality, the tables are loaded with foreign key constraints that enforce data reference integrity. &amp;lt;&amp;lt;Good!&amp;gt;&amp;gt;  We are not baking cakes, we are making wine. Our grapes do not arrive with handy little bar codes stamped on them. &amp;lt;&amp;lt;Will you be my new best friend? But that does imply a UPC code on the bottles, boxes and cartons. There was a wine named “Loon Lake” or some such which had a bird on a lake for the label. But they made the bar code into a stand of bull rushes on the edge of the lake, so it became part of the art work. &amp;gt;&amp;gt; I'm pretty sure you're not suggesting I assign a vehicle identification number to my grapes, but my quick Google search on your acronyms didn't give me much of a clue. Could it be that you are refering to a surrogate key?  &amp;lt;&amp;lt;The VIN (Vehicle Identification Number)  is just a good example of a universal industry standard identifier.  It is on your automobile, the DVM reoccurs, the insurance policy, etc. People can verify it instantly  ---  all Fords have 'F' in one certain position, etc. So I know that if the VIN says this is a Honda Diablo or a Lamborghini Civic, the VIN is wrong. I can validate it by calling the manufacturer, CarFax, my state DVM, etc. and see if the car actually exists.  Try to do that with an IDENTITY.&amp;gt;&amp;gt; So if I insert underscores in my column names, I will be able to get the results I need? Who knew that such a simple fix would do the trick. I feel so stupid now. &amp;lt;&amp;lt;Your eyes jump to Uppercase letters, so camelCase gives you a “twitch”  when you read code.  I cover some of the research on this that was done while I was at AIRMICS; the bottom line after two years of collecting all the research was a set of formatting rules that saved DoD  8 to 12% on the time to maintain code.  Springer has a new book on this kind of testing with modern equipment, but I am out of that research now and I am not going to spend $$$ on a book. That is part of the ISO-11179 standards.  The basic format is “[&amp;lt;role&amp;gt;_]&amp;lt;attribute&amp;gt;_&amp;lt;property&amp;gt;”  where the &amp;lt;property&amp;gt; is drawn from a vocabulary.  The example given in the  ISO document is for a “tree” which can have “tree_diameter”, “tree_species”, etc.  The &amp;lt;role&amp;gt; is used when the same attribute appears in the same table in different roles  such as “husband_emp_id” and “wife_emp_id”  in a “Marriages” relationship table. I cover all this in SQL PROGRAMMING STYLE. &amp;gt;&amp;gt; What do you recommend? &amp;lt;&amp;lt;Nothing can be more than 100%, so that sets an upper limit. How many decimal places do you measure to? Parts per million? Per billion? &amp;gt;&amp;gt; Again, S and R were used to over-simplify a process that not only receives and ships, but uses inputs and outputs to blend product and adjust inventory balances (which can be positive or negative numbers, so a negative qty is not necessarily a shipment). I could have left off the S and R but I need a way to identify actual shipments and receipts as opposed to movements and adjustments. &amp;lt;&amp;lt;Okay&amp;gt;&amp;gt; You lost me a bit here. I didn't present a Recipe table, but rather a Receipt table that stores the details of the receipts into the plant (i.e. 75% Zinfandel Grapes from Napa Valley, 25% Zinfandel Grapes from Monterey, etc) The receipt is linked to the inventory transaction via one of those evil "key" columns -- specifically TrnKey. &amp;lt;&amp;lt;This is where I got lost; I did not know about the wine part of this. So we have a receipt number that the accountants will like. Does this mean that if we receive 1000 gallons of that mix, we have “shipment details” of one tank of  750 gallons of ZN (grape code?) and a tank of 250 gallons of ZM? Or are they blended together in the shipment? &amp;gt;&amp;gt; Think of it this way. Product #123 is 2010 Napa Valley Merlot Wine. On day 1, we received 1000 GA (GA is the UOM for Gallons)  and it was sourced from grapes from Farmer Joe in Napa Valley (85%) and grapes from Farmer Sam in Monterey (15%). On day 2, we bottled 100 gallons of product #123 and we must prove the percents in the bottle. On day 3 received 500 GA of product #123 but its grapes were sourced from Farmer John in Napa Valley (95%) and Farmer Dick in Bakersfield (5%). It is all mixed together in the same tank. On day 4 we bottle another 100 GA, but we need to prove the latest percents -- how much from Napa Valley and how much from Bakersfield. &amp;lt;&amp;lt; So this is a running version of the “water &amp; wine puzzle”! http://en.wikipedia.org/wiki/Wine/water_mixing_problem Let me p[lay with that. Do you have Denali or plans to move to it?  DB2? Oracle?  A stronger SQL product? The reason I ask is that SQL with the [ROW | RANGE] subclause  and it makes this sort of thing much easier. No, 'gal' is the ANSI Standard abbreviation for US Gallon, not to be confused with an Imperial gallon. Ever go thru the “US Pint vs UK pint vs liter” fight in bars with fair pour rules?  I figured that you would be metric since we have had  750 ml bottles, and all that stuff, for decades now.  And a liter of water/beer is a kilogram, so you can use a scale for home brewing. &amp;gt;&amp;gt; Perhaps the transition to SQL for dinosaur COBOL developers would be easier if their questions were not attacked with arrogance and petty insults. &amp;lt;&amp;lt;Have you seen my tee shirts? “Viral Marketing does not work! Tell everyone you know!” and “Social skills are overrated, you meathead!” I am adversarial by nature and have a reputation for it.  My wife is an ordained Soto Zen priest and she hits people with a stick!  But on the other hand, I do not charge my consulting rates in SQL forums :) </description><pubDate>Mon, 05 Sep 2011 16:27:57 GMT</pubDate><dc:creator>CELKO</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Here's a mod which works across different products with different numbers of ingredients:[code="sql"]USE tempdbGOCREATE TABLE Transactions(        trnKey                  INTEGER         NOT NULL,        trnTranDate             DATETIME        NOT NULL,        trnProductID			INTEGER         NOT NULL,        trnShipRecv             CHAR(1)         NOT NULL,        trnTranQty              DECIMAL(18,5)	NOT NULL,        trnTranUOM              CHAR(2)         NOT NULL,        PRIMARY KEY (trnKey)        )CREATE TABLE Ingredients(        ingKey                  INTEGER         NOT NULL,        ingIngrientDesc VARCHAR(20)				NOT NULL,        PRIMARY KEY (ingKey)        )                CREATE TABLE Receipts(        recKey                  INTEGER         NOT NULL,        recTrnKey               INTEGER         NOT NULL,        recIngKey               INTEGER         NOT NULL,        recIngPct               DECIMAL(18,5)   NOT NULL,        PRIMARY KEY (recKey)        )        INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT 1,'Ingredient A'INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT 2,'Ingredient B'INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT 3,'Ingredient C'INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT 4,'Ingredient D'                INSERT INTO Transactions(trnKey, trnTranDate, trnProductID, trnShipRecv, trnTranQty, trnTranUOM)SELECT  1, '1/1/2011', 123, 'R', 1000, 'GA' UNION ALL                                SELECT  2, '1/2/2011', 123, 'S', -100, 'GA' UNION ALL    SELECT  3, '1/2/2011', 123, 'S', -200, 'GA' UNION ALL    SELECT  4, '1/3/2011', 123, 'R', 500, 'GA' UNION ALLSELECT  5, '1/4/2011', 123, 'S', -100, 'GA' UNION ALLSELECT  6, '1/1/2011', 124, 'R', 100, 'GA' UNION ALL                                SELECT  7, '1/2/2011', 124, 'S', -50, 'GA' UNION ALL    SELECT  8, '1/3/2011', 124, 'R', 100, 'GA' UNION ALLSELECT  9, '1/4/2011', 124, 'S', -150, 'GA'                INSERT INTO Receipts(recKey, recTrnKey, recIngKey, recIngPct)SELECT  1, 1, 1, 75 UNION ALLSELECT  2, 1, 2, 25 UNION ALLSELECT  3, 4, 1, 80 UNION ALL               SELECT  4, 4, 2, 10 UNION ALL              SELECT  5, 4, 3, 10 UNION ALL SELECT  6, 6, 1, 78 UNION ALLSELECT  7, 6, 2, 22 UNION ALLSELECT  8, 8, 1, 80 UNION ALL               SELECT  9, 8, 2, 10 UNION ALL              SELECT 10, 8, 3, 5 UNION ALL              SELECT 11, 8, 4, 5; IF(OBJECT_ID('TempDB..#PreparedData') IS NOT NULL) DROP TABLE #PreparedData;-- Prepare a temporary table which has everything we need in place to perform the calculation;WITH ABC AS (	SELECT 		seq = ROW_NUMBER() OVER(ORDER BY t.trnProductID, t.trnKey, ingIngrientDesc), 		NewKey = DENSE_RANK() OVER (PARTITION BY t.trnProductID ORDER BY t.trnProductID, t.trnTranDate, t.trnShipRecv),		ingCount = COUNT(*) OVER(PARTITION BY t.trnProductID, t.trnKey),		t.trnKey, 		t.trnTranDate, 		t.trnProductID, 		t.trnShipRecv, 		t.trnTranQty, 		t.trnTranUOM, 		i.ingIngrientDesc, 		r.recIngPct 	FROM Transactions t	INNER JOIN (		SELECT trnProductID, ingKey, ingIngrientDesc			FROM Transactions t		INNER JOIN Receipts r ON r.recTrnKey = t.trnKey 		INNER JOIN Ingredients i ON i.ingKey = r.recIngKey		GROUP BY trnProductID, ingKey, ingIngrientDesc	) i ON i.trnProductID = t.trnProductID	LEFT JOIN Receipts r ON r.recTrnKey = t.trnKey AND i.ingKey = r.recIngKey)SELECT 	seq,  	NewKey,	ingCount, 	trnKey, 	trnTranDate, 	trnProductID, 	trnShipRecv, 	trnTranQty, 	trnTranUOM, 	ingIngrientDesc, 	recIngPct		= CASE WHEN trnShipRecv = 'R' THEN ISNULL(recIngPct,0) END,	[Ingr Qty]		= CAST(CASE WHEN trnShipRecv = 'R' THEN ISNULL(trnTranQty*recIngPct,0)/100.00000 END AS DECIMAL(18,5)), 	[Ingr Pct]		= CAST(CASE WHEN trnShipRecv = 'R' THEN ISNULL(recIngPct,0) END AS DECIMAL(9,5)),	[Inventory Qty] = CAST(CASE WHEN NewKey = 1 THEN ISNULL(trnTranQty*recIngPct,0)/100.00000 ELSE NULL END AS DECIMAL(18,5)),	[Inventory Pct] = CAST(CASE WHEN NewKey = 1 THEN ISNULL(recIngPct,0) ELSE NULL END AS DECIMAL(9,5)),	 	TotalVolume		= CASE WHEN NewKey = 1 THEN trnTranQty ELSE NULL END INTO #PreparedData FROM ABC  ORDER BY trnProductID, trnKey, ingIngrientDesc-- This index is required for sensible performanceCREATE UNIQUE CLUSTERED INDEX [CX_seq] ON #PreparedData (seq ASC)--SELECT * FROM #PreparedData -- 31 rows-- run the calculation: the result is an output set.;WITH Calculator AS (SELECT 	seq, NewKey, ingCount, trnKey, trnTranDate, trnProductID, 	trnShipRecv, trnTranQty, trnTranUOM, ingIngrientDesc, recIngPct,	[Ingr Qty], 	[Ingr Pct],	[Inventory Qty],	[Inventory Pct],	TotalVolume	 FROM #PreparedDataWHERE trnKey = 1 -- seq IN (1,2,3) -- first 3 rows are first block for this productUNION ALLSELECT 	tr.seq, tr.NewKey, tr.ingCount, tr.trnKey, tr.trnTranDate, tr.trnProductID, 	tr.trnShipRecv, tr.trnTranQty, tr.trnTranUOM, tr.ingIngrientDesc, tr.recIngPct,	[Ingr Qty] = CAST(CASE 		WHEN tr.trnShipRecv = 'R' THEN tr.[Ingr Qty] 		WHEN tr.trnShipRecv = 'S' THEN tr.trnTranQty*lr.[Inventory Pct]/100.00000  		END AS DECIMAL(18,5)), 	[Ingr Pct] = CAST(CASE 		WHEN tr.trnShipRecv = 'R' THEN tr.[Ingr Pct] 		WHEN tr.trnShipRecv = 'S' THEN lr.[Inventory Pct]  		END AS DECIMAL(9,5)), 	[Inventory Qty] = CAST(CASE		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN tr.[Ingr Qty] 		WHEN tr.trnShipRecv = 'R' THEN lr.[Inventory Qty]+tr.[Ingr Qty] 		  		WHEN tr.trnShipRecv = 'S' THEN lr.[Inventory Qty]+(tr.trnTranQty*lr.[Inventory Pct]/100.00000)		 		END AS DECIMAL(18,5)),	[Inventory Pct] = CAST(CASE 		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN tr.[Inventory Pct] 		WHEN tr.trnShipRecv = 'R' THEN 100.00000*(lr.[Inventory Qty]+tr.[Ingr Qty]) / (tr.trnTranQty+lr.[TotalVolume])   		WHEN tr.trnShipRecv = 'S' THEN lr.[Inventory Pct]  		END AS DECIMAL(9,5)),	TotalVolume	= CAST(CASE 		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN tr.trnTranQty 		ELSE tr.trnTranQty+lr.[TotalVolume] 		END AS DECIMAL(18,5))		 FROM #PreparedData tr -- this setINNER JOIN Calculator lr -- last set 	ON lr.seq + tr.ingCount = tr.seq -- n rows at a time, where n = max number of ingredients for this product) SELECT  	[Date]		= trnTranDate,	[Ship/Recv] = trnShipRecv,		[Product]	= trnProductID,		[Tran Qty]	= trnTranQty,		[UOM]		= trnTranUOM,		[Ingredient]= ingIngrientDesc,		[Ingr Pct],		[Ingr Qty],		[Inventory Qty],		[Inventory Pct]FROM CalculatorWHERE [Ingr Qty] &amp;lt;&amp;gt; 0 ORDER BY seq-- About 3000 rows/sDROP TABLE ReceiptsDROP TABLE TransactionsDROP TABLE Ingredients[/code]</description><pubDate>Mon, 05 Sep 2011 10:06:35 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>[quote][b]gcresse (9/1/2011)[/b][hr]Oops.  You are correct, I have a mistake in the spreadsheet calculations. I forgot to mention in my original post that the product is liquid and stored in a tank.  As new receipts come in, they are mixed with the current inventory, changing the overall ingredient percents, so that the next shipment must take into consideration the new percents. I have been looking at Jeff Moden's article about Quirky Updates and wonder if somehow I can use that logic.  The biggest issue I see is that I have multiple "running total" variables to keep track of (several ingredients for the same product) so I'm not sure if I can make it work.  Has anyone used any variation of the Quirky Update that might work for this?[/quote]Thanks for the confirmation - The formulas in J7 and J8 are incorrect, consequently the figures in rows 10 and 11 are incorrect also. With that out of the way, here's a cursorless solution:[code="sql"]IF(OBJECT_ID('TempDB..#PreparedData') IS NOT NULL) DROP TABLE #PreparedData;-- Prepare a temporary table which has everything we need in place to perform the calculation;WITH ABC AS (	SELECT 		NewKey = DENSE_RANK() OVER (PARTITION BY t.trnProductID ORDER BY t.trnProductID, t.trnTranDate, t.trnShipRecv), 		t.trnKey, 		t.trnTranDate, 		t.trnProductID, 		t.trnShipRecv, 		t.trnTranQty, 		t.trnTranUOM, 		i.ingIngrientDesc, 		recIngPct = CASE WHEN trnShipRecv = 'R' AND r.recIngPct IS NULL THEN 0 ELSE r.recIngPct END,		[Ingr Qty]	= CAST(NULL AS DECIMAL(18,5)), 		[Ingr Pct]	= CAST(NULL AS DECIMAL(7,3)),		[Inventory Qty] = CAST(NULL AS DECIMAL(18,5)),		[Inventory Pct] = CAST(NULL AS DECIMAL(7,3))	 	FROM Transactions t	INNER JOIN (		SELECT trnProductID, ingKey, ingIngrientDesc		FROM Transactions t		INNER JOIN Receipts r ON r.recTrnKey = t.trnKey 		INNER JOIN Ingredients i ON i.ingKey = r.recIngKey		GROUP BY trnProductID, ingKey, ingIngrientDesc	) i ON i.trnProductID = t.trnProductID	LEFT JOIN Receipts r ON r.recTrnKey = t.trnKey AND i.ingKey = r.recIngKey)SELECT 	seq = ROW_NUMBER() OVER(ORDER BY trnProductID, trnKey, ingIngrientDesc), 	NewKey,	Batchkey = ROW_NUMBER() OVER(PARTITION BY trnProductID, trnKey ORDER BY ingIngrientDesc), 	trnKey, 	trnTranDate, 	trnProductID, 	trnShipRecv, 	trnTranQty, 	trnTranUOM, 	ingIngrientDesc, 	recIngPct,	[Inventory Qty] = CASE WHEN NewKey = 1 THEN recIngPct/100.00000*trnTranQty ELSE NULL END,	[Inventory Pct] = CASE WHEN NewKey = 1 THEN recIngPct ELSE NULL END,	 	[Ingr Qty] = CASE WHEN NewKey = 1 THEN recIngPct/100.000*trnTranQty ELSE NULL END, 	[Ingr Pct] = CASE WHEN NewKey = 1 THEN recIngPct ELSE NULL END,	TotalVolume = CASE WHEN NewKey = 1 THEN trnTranQty ELSE NULL END INTO #PreparedData FROM ABC  ORDER BY trnProductID, trnKey, ingIngrientDesc-- put an index on this to make it faster:CREATE UNIQUE CLUSTERED INDEX [CX_seq] ON #PreparedData (seq ASC)-- run the calculation: the result is an output set.;WITH Calculator AS (SELECT 	seq, 	NewKey,	Batchkey, 	trnKey, 	trnTranDate, 	trnProductID, 	trnShipRecv, 	trnTranQty, 	trnTranUOM, 	ingIngrientDesc, 	recIngPct,	[Ingr Qty] = CAST([Ingr Qty] AS DECIMAL(18,5)), 	[Ingr Pct] = CAST([Ingr Pct] AS DECIMAL(7,3)), 	[Inventory Qty] = CAST([Inventory Qty] AS DECIMAL(18,5)),	[Inventory Pct] = CAST([Inventory Pct] AS DECIMAL(7,3)),	TotalVolume	 FROM #PreparedDataWHERE seq IN (1,2,3) -- first 3 rows are first block for this productUNION ALLSELECT 	tr.seq, 	tr.NewKey, 	tr.Batchkey, 	tr.trnKey, 	tr.trnTranDate, 	tr.trnProductID, 	tr.trnShipRecv, 	tr.trnTranQty, 	tr.trnTranUOM, 	tr.ingIngrientDesc, 	recIngPct = CASE 		WHEN tr.trnShipRecv = 'R' THEN tr.recIngPct 		WHEN tr.trnShipRecv = 'S' THEN NULL --lr.[Inventory Pct]  		END,	[Ingr Qty] = CAST(CASE 		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN tr.[Ingr Qty] -- first tran for ingredient 		WHEN tr.trnShipRecv = 'R' THEN tr.trnTranQty*tr.recIngPct/100.00000 		WHEN tr.trnShipRecv = 'S' THEN tr.trnTranQty*lr.[Inventory Pct]/100.00000  		END AS DECIMAL(18,5)), 	[Ingr Pct] = CAST(CASE 		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN tr.[Ingr Pct] 		WHEN tr.trnShipRecv = 'R' THEN tr.recIngPct 		WHEN tr.trnShipRecv = 'S' THEN lr.[Inventory Pct]  		END AS DECIMAL(7,3)), 	[Inventory Qty] = CAST(CASE		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN (tr.trnTranQty*tr.recIngPct/100.00000)				WHEN tr.trnShipRecv = 'R' THEN lr.[Inventory Qty]+(tr.trnTranQty*tr.recIngPct/100.00000)		  		WHEN tr.trnShipRecv = 'S' THEN lr.[Inventory Qty]+(tr.trnTranQty*lr.[Inventory Pct]/100.00000)		 		END AS DECIMAL(18,5)),	[Inventory Pct] = CAST(CASE 		WHEN tr.trnShipRecv = 'R' AND tr.NewKey = 1 THEN tr.[Inventory Pct] 		WHEN tr.trnShipRecv = 'R' THEN 100.00000*(lr.[Inventory Qty]+(tr.trnTranQty*tr.recIngPct/100.00000)) / (tr.trnTranQty+lr.[TotalVolume])   		WHEN tr.trnShipRecv = 'S' THEN lr.[Inventory Pct]  		END AS DECIMAL(7,3)),	TotalVolume  = CAST(CASE 		WHEN tr.NewKey = 1 AND tr.trnShipRecv = 'R' THEN tr.trnTranQty 		WHEN tr.NewKey &amp;gt; 1  THEN tr.trnTranQty+lr.[TotalVolume] 		ELSE NULL END AS DECIMAL(18,5))		 FROM #PreparedData tr -- this set of 3 rowsINNER JOIN Calculator lr -- last set of 3 rows 	ON lr.seq+3 = tr.seq -- 3 rows at a time) SELECT 	[Date] = trnTranDate,	[Ship/Recv] = trnShipRecv,		[Product] = trnProductID,		[Tran Qty] = trnTranQty,		[UOM] = trnTranUOM,		[Ingredient] = ingIngrientDesc,		[Ingr Pct],		[Ingr Qty],		[Inventory Qty],		[Inventory Pct]FROM Calculator ORDER BY seq[/code]If this works ok on a decent set of sample data, then there's scope for altering it to run over different products.You could do this with the QU if you pivoted the ingredient rows to columns.</description><pubDate>Mon, 05 Sep 2011 04:19:39 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Thanks for your reply, R.P.Rozema. [quote]Isn't the essence of your problem that you are trying to calculate off of percentages of a volume per shipment? In other words, shouldn't you store absolute quantities of the components inserted instead of percentages of the received shipment? I.e. from the volume and percentages of a receipt you can easily calculate the absolute quantities of each component and merge those into the quantities already there (very much like the liquids themselves). Calculating the percentages over the contents over the entire tank or a partial shipment taken from it will be an easy task given the volume of the tank/shipment and the absolute quantities in your table.[/quote]Yes, you are correct.  If I could store the running balances of the individual components at each transactions, my problem would be solved.  But, users are not perfect, and they often discover that they made a mistake (or a receiving document was incorrect) and six months ago the product that came in as 100% (1000 GA) of Napa Valley Zinfanel was actually only 75% Napa Valley Zinfandel and 25% Bakersfield Merlot.  All the component qtys stored for the last 6 months are incorrect once the mistake is discovered.  In reality, I don't use a cursor for this.  We have a nightly batch job that builds the running totals beginning from the earliest date that any transaction was changed.  This data is stored in a data warehouse and is growing exponentially large, requiring more and more database space.  At one time we did use the cursor approach but the performance was unacceptable, which is why the data warehouse method was developed.  I was hoping to find an alternative to the data warehousing approach (users have to wait till the next day to get the most accurate data, and if we have to make a correction farther back in time than, say, 1 year, the process takes many hours) and since the cursor approach already failed, I knew that was out of the question.</description><pubDate>Fri, 02 Sep 2011 12:07:16 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Thanks for your kind reply, Celko.  Your insight into the fact that this system was originally written in COBOL and converted to VB/SQL by the COBOL developer is amazing.  Were you once beaten up by a gang of COBOL geeks?[quote]Never put the table name as a column prefix (that was COBOL record definition not SQL). [/quote]This particular naming convention is required in our system due to a third-party auditing program that uses triggers to write to an audit table whenever a column value is inserted/updated/deleted.  If we duplicate column names between tables, that program doesn't record the audit row correctly.[quote]There is no such crap as a magical genetic “key” (that was a record number in mag tape files or pointer chains in network DBMS, not SQL).[/quote]Perhaps it is my fault for over-simplifying the sample data.  In reality, the "key" columns in these tables are IDENTITY surrogate keys.  I did not create them that way in the sample data because I wanted to control the values to simplify.  If "key" is not the correct term to describe a surrogate key, then what is?  Are surrogate keys now out of style?  Because before we introduced them, users had to make up their own identifiers and they kept hand-written logs or Excel spreadsheets... some of them probably chiseled the identifiers in stone tablets as a left-over from the old COBOL days.[quote]Why did there no DRI or other constraints? (answer: files do not have them). [/quote]Again, my fault for over-simplifying.  In reality, the tables are loaded with foreign key constraints that enforce data reference integrity.[quote]SQL Programmers use for particular keys; we use a VIN, not a silly invented “autokey”, etc. Let's use the UPC code to identify the Ingredients instead of a silly pseudo-pointer.[/quote]Again, my fault for not providing the complete details of our products in an attempt to simplify.  We are not baking cakes, we are making wine.  Our grapes do not arrive with handy little bar codes stamped on them.  I'm pretty sure you're not suggesting I assign a vehicle identification number to my grapes, but my quick Google search on your acronyms didn't give me much of a clue.  Could it be that you are referreing to a surrogate key?[quote]The use of camelCase is also out of date, a bitch to read and not ISO.[/quote]So if I insert underscores in my column names, I will be able to get the results I need?  Who knew that such a simple fix would do the trick.  I feel so stupid now.[quote]Why did you do a percentage with DECIMAL(18,5)? [/quote]What do you recommend? [quote]Likewise, “ship_recv” looks like a mag tape file bit flag; an SQL programmer would have a received date that is NULL when the shipment is still in process. But wait! This is a redundancy status for input and output to inventory! The sign of the quantity tells us 'R' or 'S' without loss of data integrity, like you HAVE NOW. [/quote]Again, S and R were used to over-simplify a process that not only receives and ships, but uses inputs and outputs to blend product and adjust inventory balances (which can be positive or negative numbers, so a negative qty is not necesarily a shipment). I could have left off the S and R but I need a way to identify actual shipments and receipts as opposed to movements and adjustments.[quote]A recipe has many ingredients so that gives us a two column real key instead of a fake mag tape record number. This is a relationship, so we need DRI in this table. But why does the ticket number have any thing to do with baking the cake? CREATE TABLE Recipes(recipe_nbr INTEGER NOT NULL, upc CHAR(13) NOT NULL REFERENCES Ingredients(upc), PRIMARY KEY (recipe_nbr, upc), recipe_pct DECIMAL(8,5) NOT NULL CHECK(recipe_pct BETWEEN 00.00001 AND 100.00000));[/quote]You lost me a bit here.  I didn't present a Recipe table, but rather a Receipt table that stores the details of the receipts into the plant (i.e. 75% Zinfandel Grapes from Napa Valley, 25% Zinfandel Grapes from Monterey, etc)  The receipt is linked to the inventory transaction via one of those evil "key" columns -- specifically TrnKey.[quote]Now when we get to the Inventory, it looks like you are trying to do a COBOL record structure again, not SQL. In SQL all column are scalar and this looks like you are cramming upc codes 1, 2 and 3 into a single column!! Besides spitting on Dr. Codd's grave, we have no idea to which of the three ingredients the quantity applies. Also, what is a “GA”; I do not know that unit. INSERT INTO Inventory_Transactions (inventory_ticket_nbr, ticket_date, upc, ticket_qty, uom)VALUES (1, '2011-01-01', '123', 1000, 'GA'), (2, '2011-01-02', '123', -100, 'GA'), (3, '2011-01-03', '123', 500, 'GA'), (4, '2011-01-04', '123', -100, 'GA');[/quote]Somehow you have gotten the idea that product #123 is actually referring to ingredients A, B, and C.  Think of it this way.  Product #123 is 2010 Napa Valley Merlot Wine.  On day 1, we received 1000 GA (GA is the UOM for Gallons) and it was sourced from grapes from Farmer Joe in Napa Valley (85%) and grapes from Farmer Sam in Monterey (15%).  On day 2, we bottled 100 gallons of product #123 and we must prove the percents in the bottle.  On day 3 received 500 GA of product #123 but its grapes were sourced from Farmer John in Napa Valley (95%) and Farmer Dick in Bakersfield (5%).  It is all mixed together in the same tank.  On day 4 we bottle another 100 GA, but we need to prove the latest percents -- how much from Napa Valley and how much from Bakersfield.Perhaps the transition to SQL for dinosaur COBOL developers would be easier if their questions were not attacked with arrogance and petty insults.</description><pubDate>Fri, 02 Sep 2011 11:48:56 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Isn't the essence of your problem that you are trying to calculate off of percentages of a volume per shipment? In other words, shouldn't you store absolute quantities of the components inserted instead of percentages of the received shipment? I.e. from the volume and percentages of a receipt you can easily calculate the absolute quantities of each component and merge those into the quantities already there (very much like the liquids themselves). Calculating the percentages over the contents over the entire tank or a partial shipment taken from it will be an easy task given the volume of the tank/shipment and the absolute quantities in your table.The only thing that could be of worry if this is a continuous process, are rounding errors. I can imagine that some components are added in very large percentages, whereas others would be inserted in very minor quantities only. Actions like taking shipments from the tank will make rounding errors have a bigger impact. If I were in control I would suggest to periodically empty the entire tank to avoid these rounding errors grow out of control. But if this is a production facility you most likely already do something like this, and thus your software rounding errors will be reset with every cleaning of the tank too.</description><pubDate>Fri, 02 Sep 2011 03:13:18 GMT</pubDate><dc:creator>R.P.Rozema</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>I have products that are made up of different ingredient components. The percentage of the ingredients are defined when the products are received into inventory. When we ship the products, we have to report the ingredient percents that were in the product when it shipped. The ingredients vary for the same product on each receipt, so the percents need to be re-calculated for each transaction. Attached is spreadsheet of a very simple example.The following code creates sample data that demonstrates my challenge. Without using a cursor, is there a way to efficiently (read: quickly) return the values from the Inventory [no such table in your code] Pct column of the attached spreadsheet? This sample data is very small. In the real world, I'm dealing with thousands of products and each can have hundreds of transactions and each can have hundreds of ingredients, though I only need to deal with 1 product at a time. Any ideas are greatly appreciated. Thanks.Thanks for the DDL. Please learn ISO-11179 naming rules and basic data modeling. We have DATE data types and use ISO-8601 dates. We have ANSI/ISO Row constructors. You are using cursors because you are writing 1950's file systems code in SQL. Here is the skeleton analysis. Never put the table name as a column prefix (that was COBOL record definition not SQL). There is no such crap as a magical genetic “key” (that was a record number in mag tape files or pointer chains in network DBMS, not SQL). Why did there no DRI or other constraints? (answer: files do not have them). SQL Programmers use for particular keys; we use a VIN, not a silly invented “autokey”, etc. Let's use the UPC code to identify the Ingredients instead of a silly pseudo-pointer. The use of camelCase is also out of date, a bitch to read and not ISO. Why did you do a percentage with DECIMAL(18,5)? That just invites huge errors. Likewise, “ship_recv” looks like a mag tape file bit flag; an SQL programmer would have a received date that is NULL when the shipment is still in process. But wait! This is a redundancy status for input and output to inventory!  The sign of the quantity tells us 'R' or 'S' without loss of data integrity, like you HAVE NOW. CREATE TABLE Inventory_Transactions(inventory_ticket_nbr INTEGER NOT NULL PRIMARY KEY, ticket_date DATE DEFAULT CURRENT_TIMESTAMP NOT NULL, upc CHAR(13) NOT NULL NOT NULL, ticket_qty DECIMAL(18,5) NOT NULL, uom CHAR(2) NOT NULL);CREATE TABLE Ingredients(upc CHAR(13) NOT NULL PRIMARY KEY, ingredient_desc VARCHAR(20) NOT NULL);A recipe has many ingredients so that gives us a two column real key instead of a fake mag tape record number. This is a relationship, so we need DRI in this table. But why does the ticket number have any thing to do with baking the cake? CREATE TABLE Recipes(recipe_nbr INTEGER NOT NULL, upc CHAR(13) NOT NULL   REFERENCES Ingredients(upc), PRIMARY KEY (recipe_nbr, upc), recipe_pct DECIMAL(8,5) NOT NULL  CHECK(recipe_pct BETWEEN 00.00001 AND 100.00000));Her is the current syntax for insertions. You inserted rows one at a time, like punch cards in 1950's COBOL and not sets.INSERT INTO Ingredients(upc, ingredient_desc) VALUES ('1','Ingredient A'), ('2','Ingredient B'), ('3', 'Ingredient C');Now when we get to the Inventory, it looks like you are trying to do a COBOL record structure again, not SQL.  In SQL all column are scalar and this looks like you are cramming upc codes 1, 2 and 3 into a single column!! Besides spitting on Dr. Codd's grave, we have no idea to which of the three ingredients the quantity applies. Also, what is a “GA”; I do not know that unit.  INSERT INTO Inventory_Transactions (inventory_ticket_nbr, ticket_date, upc, ticket_qty, uom)VALUES (1, '2011-01-01', '123', 1000, 'GA'),        (2, '2011-01-02', '123', -100, 'GA'),       (3, '2011-01-03', '123', 500, 'GA'),        (4, '2011-01-04', '123', -100, 'GA');We can build an inventory view on this, once it is normalizedCREATE VIEW Current_Inventory_Levels (upc, onhand_qty, onhand_uom))AS SELECT .. FROM .. WHERE ticket_date &amp;lt;= CAST (CURRENT_TIMESTAMP AS DATE); Let get that fixed later. The recipes are now easy; whyd id you do the math outside the table? Answer: COBOL was not good at math.  INSERT INTO Recipes (recipe_nbr, upc, recipe_pct)VALUES('42', '1', .75), ('42', '2', .25),      ('43', '1', .80), ('43', '2', .10), ('43', '3', .10);So a #42 cake is 75% ingredient A and 25% ingredient B, etc. What you will do is called a relational division. The divisor is a recipe, the dividend is the inventory. No cursors, no loop and no more COBOL, please!</description><pubDate>Thu, 01 Sep 2011 23:01:38 GMT</pubDate><dc:creator>CELKO</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>[quote]The quirky update will handle more than one running total...seehttp://www.sqlservercentral.com/articles/T-SQL/68467/ Fig 19 in the article[/quote]Thanks, J.  That is the very article that I'm reading (for the second time... only a dozen more to go :-D).  When I say multiple variables need to be updated, I don't mean in the way that the article is updating both a running total and a running count.  I don't know if you looked at my sample data or the spreadsheet, but basically it's the same variable but with any number of potential values.  I receive product with 75% Ingredient A and 25% Ingredient B then later I receive more of the same product, but this time with 80% Ingredient A, 10% Ingredient B, and 10% Ingredient C.  I need to re-calculate the overall percents (combine the ingredient percents from the first receiving with the ingredient percents from the second receiving).  If I knew there would only ever be 3 ingredients, I could DIM @IngrArunningTotal, @IngrBrunningTotal, @IngrCrunningTotal, but there can be any number of ingredients on any number of receivings.  I thought perhaps I could use a temporary table to store the running totals instead of the variables, but "RULE #5. DO NOT USE JOINS" from Jeff's article indicates that I probably can't do that... Back to reading...</description><pubDate>Thu, 01 Sep 2011 16:24:39 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>[quote][b]gcresse (9/1/2011)[/b][hr]The spreadsheet calculations are correct.  I forgot to mention in my original post that the product is liquid and stored in a tank.  As new receipts come in, they are mixed with the current inventory, changing the overall ingredient percents, so that the next shipment must take into consideration the new percents. I have been looking at Jeff Moden's article about Quirky Updates and wonder if somehow I can use that logic.  The biggest issue I see is that I have multiple "running total" variables to keep track of (several ingredients for the same product) so I'm not sure if I can make it work.  Has anyone used any variation of the Quirky Update that might work for this?[/quote]The quirky update will handle more than one running total...see[url]http://www.sqlservercentral.com/articles/T-SQL/68467/[/url]  Fig 19 in the articleI would suggest that you read the article at least twice (or even twenty times :-D ) and then make an attempt in a safe (non prod) environment...I am sure that if you get stuck and post back the code you have tried , then I would expect someone, if not Jeff himself, wil chime in.Based on my own experience ....if you do have problems and need to post back, then please provide a decent set of test data that is easy for us to use (see link in my sig) and also, do not try to over simplify your table and data....this quite often leads to you not getting the results you really need.The quirky update has a lot of rules that MUST be used.....so read the article again :-D</description><pubDate>Thu, 01 Sep 2011 16:04:10 GMT</pubDate><dc:creator>J Livingston SQL</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Oops.  You are correct, I have a mistake in the spreadsheet calculations. I forgot to mention in my original post that the product is liquid and stored in a tank.  As new receipts come in, they are mixed with the current inventory, changing the overall ingredient percents, so that the next shipment must take into consideration the new percents. I have been looking at Jeff Moden's article about Quirky Updates and wonder if somehow I can use that logic.  The biggest issue I see is that I have multiple "running total" variables to keep track of (several ingredients for the same product) so I'm not sure if I can make it work.  Has anyone used any variation of the Quirky Update that might work for this?</description><pubDate>Thu, 01 Sep 2011 15:40:27 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>[quote]based on the sample code you gave, for the shipment on 2011-01-04 of qty 100 of product 123.....how do we know which receipt this was taken from?[/quote]The product is liquid and stored/mixed together in a tank.  The receiving qty is mixed together with the current inventory, effectively changing the overall percents with each receipt.</description><pubDate>Thu, 01 Sep 2011 07:48:36 GMT</pubDate><dc:creator>gcresse</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>The calculations in your spreadsheet appear to be incorrect, this is what I think it should look like:[code="xml"][font="Courier New"]Ingr Pct          Ingr Qty	Inventory Qty           Inventory Pct75.00              750              750                    75.0025.00              250              250                    25.0075.00              -75              675                    75.0025.00              -25              225                    25.0080.00             400              1075                   76.7910.00             50               275                    19.6410.00             50               50                     3.5776.79             -76.78571429     998.2142857            76.7919.64             -19.64285714     255.3571429            19.643.57              -3.571428571     46.42857143            3.57[/font][/code]It's possible to model most of your required results by adding rows to the receipts table, like this:INSERT INTO Receipts(recKey, recTrnKey, recIngKey, recIngPct)SELECT  1, 1, 1, 75 UNION ALLSELECT  2, 1, 2, 25 UNION ALLSELECT  3, 2, 1, 75 UNION ALLSELECT  4, 2, 2, 25 UNION ALLSELECT  5, 3, 1, 80 UNION ALL               SELECT  6, 3, 2, 10 UNION ALL              SELECT  7, 3, 3, 10 UNION ALL               SELECT  8, 4, 1, 80 UNION ALL               SELECT  9, 4, 2, 10 UNION ALL              SELECT  10, 4, 3, 10  I'm guessing that since these are shipments, you don't want them here - presumably you want the solution to "fabricate" them instead? </description><pubDate>Thu, 01 Sep 2011 03:33:38 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>Hibased on the sample code you gave, for the shipment on 2011-01-04 of qty 100 of product 123.....how do we know which receipt this was taken from?</description><pubDate>Thu, 01 Sep 2011 01:31:36 GMT</pubDate><dc:creator>J Livingston SQL</dc:creator></item><item><title>Calculate component percents without a cursor</title><link>http://www.sqlservercentral.com/Forums/Topic1168462-392-1.aspx</link><description>I have a challenge that I have not been able to solve (without using a cursor).  I have products that are made up of different ingredient components.  The percentage of the ingredients are defined when the products are received into inventory.  When we ship the products, we have to report the ingredient percents that were in the product when it shipped.  The ingredients vary for the same product on each receipt, so the percents need to be re-calculated for each transaction. Attached is spreadsheet of a very simple example.The following code creates sample data that demonstrates my challenge.  Without using a cursor, is there a way to efficiently (read: quickly) return the values from the Inventory Pct column of the attached spreadsheet?  This sample data is very small.  In the real world, I'm dealing with thousands of products and each can have hundreds of transactions and each can have hundreds of ingredients, though I only need to deal with 1 product at a time.  Any ideas are greatly appreciated.  Thanks.[code="sql"]CREATE TABLE Transactions(	trnKey			INTEGER			NOT NULL,	trnTranDate		DATETIME		NOT NULL,	trnProductID	INTEGER			NOT NULL,	trnShipRecv		CHAR(1)			NOT NULL,	trnTranQty		DECIMAL(18,5)	NOT NULL,	trnTranUOM		CHAR(2)			NOT NULL,	PRIMARY KEY (trnKey)	)CREATE TABLE Ingredients(	ingKey			INTEGER			NOT NULL,	ingIngrientDesc	VARCHAR(20)		NOT NULL,	PRIMARY KEY (ingKey)	)		CREATE TABLE Receipts(	recKey			INTEGER			NOT NULL,	recTrnKey		INTEGER			NOT NULL,	recIngKey		INTEGER			NOT NULL,	recIngPct		DECIMAL(18,5)	NOT NULL,	PRIMARY KEY (recKey)	)	INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT	1,'Ingredient A'INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT	2,'Ingredient B'INSERT INTO Ingredients(ingKey, ingIngrientDesc) SELECT	3,'Ingredient C'		INSERT INTO Transactions(		trnKey,		trnTranDate,		trnProductID,		trnShipRecv,		trnTranQty,		trnTranUOM)SELECT	1,		'1/1/2011',		123,		'R',		1000,		'GA'				INSERT INTO Transactions(		trnKey,		trnTranDate,		trnProductID,		trnShipRecv,		trnTranQty,		trnTranUOM)SELECT	2,		'1/2/2011',		123,		'S',		-100,		'GA'				INSERT INTO Transactions(		trnKey,		trnTranDate,		trnProductID,		trnShipRecv,		trnTranQty,		trnTranUOM)SELECT	3,		'1/3/2011',		123,		'R',		500,		'GA'				INSERT INTO Transactions(		trnKey,		trnTranDate,		trnProductID,		trnShipRecv,		trnTranQty,		trnTranUOM)SELECT	4,		'1/4/2011',		123,		'S',		-100,		'GA'		INSERT INTO Receipts(		recKey,		recTrnKey,		recIngKey,		recIngPct)SELECT	1,		1,		1,		75		INSERT INTO Receipts(		recKey,		recTrnKey,		recIngKey,		recIngPct)SELECT	2,		1,		2,		25		INSERT INTO Receipts(		recKey,		recTrnKey,		recIngKey,		recIngPct)SELECT	3,		3,		1,		80				INSERT INTO Receipts(		recKey,		recTrnKey,		recIngKey,		recIngPct)SELECT	4,		3,		2,		10				INSERT INTO Receipts(		recKey,		recTrnKey,		recIngKey,		recIngPct)SELECT	5,		3,		3,		10				SELECT	trnTranDate,		trnProductID,		trnShipRecv,		trnTranQty,		trnTranUOM,		ingIngrientDesc,		recIngPct,		trnTranQty * recIngPct / 100	AS recIngQty,		'?'								AS shipIngPct		FROM	Transactions		LEFT OUTER JOIN		Receipts ON (recTrnKey = trnKey)		LEFT OUTER JOIN		Ingredients ON (ingKey = recIngKey)ORDER BY trnTranDate				DROP TABLE ReceiptsDROP TABLE TransactionsDROP TABLE Ingredients[/code]</description><pubDate>Wed, 31 Aug 2011 20:22:54 GMT</pubDate><dc:creator>gcresse</dc:creator></item></channel></rss>