Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HTML
TABLE tbl1

ItemId Name            Quantity
1      Tomatoes        2    
2      Cucumbers       5
3      Oranges         3    
3      Oranges         1    


Table tbl2

ItemId  Name            Quantity
1       Tomatoes        3    
2       Cucumbers       5    
2       Cucumbers       10  
3       Oranges         2  

Table tbl3

ItemId  Name            Quantity
1       Tomatoes        1
1       Tomatoes        2    
2       Cucumbers       5
3       Oranges         2      

and want to output (tbl1+tbl2-tbl3) as a new temp table in stored procedure

ItemId  Name            TQuantity
1       Tomatoes        2
2       Cucumbers       15    
3       Oranges         4 
Posted
Updated 9-Jan-15 21:23pm
v2

This looks like homework so I will not give you a complete solution. Furthermore I will assume you are on SQL server.

1) Create a stored procedure[^], easy.

2) Use UNION ALL[^] to concatenate two outputs of the same structure.
Hint: How do you subtract qauntities in tbl3?

3) Use SUM[^] aggregate function to add the quantities.
Hint: What do you need to put in GROUP BY[^] clause?

4) Insert the results into a temporary table using SELECT INTO[^]. Temporary table name starts with a hash symbol (#).
Hint: How do you make the table visible outside your stored procedure?

Cheers
 
Share this answer
 
SQL
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER Procedure [dbo].[sp_rpt_StockSummary]

AS
Begin

SELECT P.ID, P.ProductName,P.ProductCode,COALESCE(cash.CashQuantity,0) + COALESCE(credit.CreditQuantity,0)- COALESCE(Oreturn.ReturnQuantity,0) as TQty

from dbo.Inv_ProductName P
	 

LEFT JOIN (select SUM(Quantity) as CashQuantity, ProductID from Inv_PurchaseCashDetails GROUP BY ProductID ) cash ON P.ID = cash.ProductID
LEFT JOIN (select SUM(Quantity) as CreditQuantity, ProductID from Inv_PurchaseCreditDetails GROUP BY ProductID) credit ON P.ID = credit.ProductID
LEFT JOIN (select SUM(Quantity) as ReturnQuantity, ProductID from Inv_PurchaseReturnDetails GROUP BY ProductID) Oreturn ON P.ID = Oreturn.ProductID

End
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900