Please start any new threads on our new 
    site at https://forums.sqlteam.com.  We've got lots of great SQL Server
    experts to answer whatever question you can come up with. 
    
        
            
                
                    
                        
                            
                                | Author | 
                                
                                 Topic  | 
                             
                            
                                    | 
                                         folumike 
                                        Starting Member 
                                         
                                        
                                        24 Posts  | 
                                        
                                        
                                            
                                            
                                             Posted - 2013-12-17 : 19:58:38
                                            
  | 
                                             
                                            
                                            | We use VB6 and MSSQL 2000 in my Office. I want to use MSSQL 2000 to the this work below.I have to tables:1.	tblTotalQty2.	tblPriceHistorytblPriceHistoryRowID	TransDate	ItemID	Quantity	Price1	01/01/2013	000001	20	5002	01/01/2013	000002	30	2003	02/01/2013	000003	50	3004	02/01/2013	000002	30	3005	04/02/2013	000001	50	5006	05/02/2013	000002	50	3007	12/03/2013	000002	10	6008	12/04/2013	000003	20	2009	13/04/2013	000001	10	40010	20/04/2013	000001	30	10011	25/05/2013	000003	20	30012	03/06/2013	000002	40	20013	22/06/2013	000001	50	40014	30/06/2013	000002	10	200tblTotalQtyDate1	ItemID	TotQty01/01/2013	000001	2001/01/2013	000002	3002/01/2013	000003	5002/01/2013	000002	3004/02/2013	000001	5005/02/2013	000002	5012/03/2013	000002	1012/04/2013	000003	2013/04/2013	000001	1020/04/2013	000001	30tblTotalQty is to show the Total Quantity of the items as at the current date selected while tblItemHistory is to show the price history of the Item Selected.I want to calculate valuation price using While loop or CursorcumQty is cummulative quantity from tblItemHistory as at selected date TotQty is total quantity from tblTotalQty as at dateWhile cumQty <= TotQtycumQty = Val(cumQty) + QuantityIf cumQty <= TotQty ThenitmVal = Quantity * Price + itmValElseitmVal = (((TotQty - (cumQty - Quantity)) * Price) + itmValExitEnd IfAvgPrice = itmVal / TotQtyPlease help me my boss in on my neckHow do I write this query in MSSQLNOTE - AvePrice is the Average Price (final result)TotQty is the Total Quantity from tblTotalQtyQuantity is the Quantity from tblPriceHistoryQuantity is the Price from tblPriceHistory | 
                                             
                                         
                                     | 
                             
       
                            
                       
                          
                            
                                    | 
                                     visakh16 
                                    Very Important crosS Applying yaK Herder 
                                     
                                    
                                    52326 Posts  | 
                                    
                                      
                                        
                                          
                                           
                                            Posted - 2013-12-18 : 07:54:50
                                          
  | 
                                         
                                        
                                          | can you post what should be your end output?------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs  | 
                                         
                                        
                                            | 
                                         
                                       
                                     | 
                                   
                            
                       
                          
                            
                                    | 
                                     folumike 
                                    Starting Member 
                                     
                                    
                                    24 Posts  | 
                                    
                                      
                                        
                                          
                                           
                                            Posted - 2013-12-18 : 10:22:17
                                          
  | 
                                         
                                        
                                          | THE FINAL OUTPUT WILL HAVE VALUES IN ITEMID & AVGPRICE. FOR EXAMPLE | 000001| 52, 000002| 60 AND SO ON.  | 
                                         
                                        
                                            | 
                                         
                                       
                                     | 
                                   
                            
                       
                          
                            
                                    | 
                                     folumike 
                                    Starting Member 
                                     
                                    
                                    24 Posts  | 
                                    
                                      
                                        
                                          
                                           
                                            Posted - 2013-12-18 : 10:22:24
                                          
  | 
                                         
                                        
                                          | THE FINAL OUTPUT WILL HAVE VALUES IN ITEMID & AVGPRICE. FOR EXAMPLE | 000001| 52, 000002| 60 AND SO ON.  | 
                                         
                                        
                                            | 
                                         
                                       
                                     | 
                                   
                            
                       
                          
                            
                                    | 
                                     visakh16 
                                    Very Important crosS Applying yaK Herder 
                                     
                                    
                                    52326 Posts  | 
                                    
                                      
                                     | 
                                   
                            
                       
                          
                            
                                    | 
                                     folumike 
                                    Starting Member 
                                     
                                    
                                    24 Posts  | 
                                    
                                      
                                        
                                          
                                           
                                            Posted - 2013-12-19 : 16:19:40
                                          
  | 
                                         
                                        
                                          quote: Originally posted by visakh16 Learn how to post a question with proper data and output. Without that its difficult to understand what your exact reuqirements arehttp://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs
  The aim is to calculate Average Price(AvgPrice) of the stock valuation using two tables:ArrayUnion and StockBalance.AvgPrice = itemValue / itemBalanceitemValue is got by iterating through ArrayUnion table as per selected date.itemBalance is got from StockBalance tablecumQty is the cummulative quantity of the arrayunion table as per the selected ItemID AND dateI expected a Output like this, but not exactlyBut am gettingItemID	AvgPrice1	61702	6754.023	8765.344	2052.735	7078.136	5283.06...But am gettingItemID	AvgPrice1	NULL2	NULL3	NULL4	NULL5	NULL6	NULL...See the script belowif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ArrayUnion]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[ArrayUnion]GOif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StockBalance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[StockBalance]GOCREATE TABLE [dbo].[ArrayUnion] (	[ItemX] [int] IDENTITY(1,1) NULL ,	[IemID] [int] NULL ,	[Date1] [datetime] NULL ,	[QtySupBal] [float] NULL ,	[InvID] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,	[Price] [money] NULL ) ON [PRIMARY]GOCREATE TABLE [dbo].[StockBalance] (	[ItemID] [int] NULL ,	[ItemBal] [float] NULL ) ON [PRIMARY]GOINSERT ArrayUnion VALUES(1,1,'01/01/2013','BEGBAL',6192.52)INSERT ArrayUnion VALUES(2,2,'01/01/2013','BEGBAL',6766.8)INSERT ArrayUnion VALUES(3,2,'02/01/2013','95422569',6766.8)INSERT ArrayUnion VALUES(4,2,'02/01/2013','95422100',6792.8)INSERT ArrayUnion VALUES(5,3,'03/01/2013','BEGBAL',9571.52)INSERT ArrayUnion VALUES(6,3,'05/01/2013','BEGBAL',6192.58)INSERT ArrayUnion VALUES(7,3,'05/01/2013','6900019885',9792.52)INSERT ArrayUnion VALUES(8,4,'06/01/2013','BEGBAL',2182.22)INSERT ArrayUnion VALUES(9,5,'07/01/2013','BEGBAL',7194.52)INSERT ArrayUnion VALUES(10,6,'08/01/2013','BEGBAL',5430.89)INSERT ArrayUnion VALUES(11,6,'14/01/2013','95422588',5430.89)INSERT StockBalance VALUES(1,3277)INSERT StockBalance VALUES(2,4554)INSERT StockBalance VALUES(3,6785)INSERT StockBalance VALUES(4,1824)INSERT StockBalance VALUES(5,5993)INSERT StockBalance VALUES(6,2792)CREATE TABLE StockValuation(ItemID NVARCHAR(100),AvgPrice MONEY)INSERT INTO StockValuation(ItemID, AvgPrice)SELECT DISTINCT ItemID, NULLFROM ArrayUnionORDER BY ItemID/* declare the local variables */DECLARE @ItemIDX NVARCHAR(100), @AvgPriceX MONEYDECLARE @itmBal FLOAT(8), @itmVal FLOAT(8), @cumQty FLOAT(8)DECLARE @ItemID NVARCHAR(100), @Date1 DATETIME, @QtySupBal FLOAT(8), @Price MONEY--SET @AvgPrice = 0SET @cumQty = 0SET @itmBal = (SELECT ItemBal FROM StockBalance)DECLARE curAvgPrice CURSOR FAST_FORWARD FORSELECT ItemID, AvgPriceFROM StockValuationORDER BY ItemIDOPEN curAvgPrice/* This is executed as long as the previous fetch succeeds. */FETCH NEXT FROM curAvgPrice INTO @ItemIDX, @AvgPriceXWHILE (@@FETCH_STATUS = 0)	-- whilst all is wellBEGIN	UPDATE StockValuation SET avgPrice = @itmVal / NULLIF(@itmBal, 0);	DECLARE curValuation CURSOR FAST_FORWARD FOR	SELECT  ItemID, Date1, QtySupBal, Price, AvgPrice	FROM ArrayUnion	ORDER BY ItemID, Date1	OPEN curValuation	-- This is executed as long as the previous fetch succeeds.	FETCH NEXT FROM curValuation INTO @ItemID, @Date1, @QtySupBal, @Price, @AvgPrice   	WHILE (@@FETCH_STATUS = 0) AND (@cumQty <= @itmBal) --whilst all is well & Cummulative Qty = Total Qty as at selected Date	BEGIN      		SET @cumQty = @cumQty + @QtySupBal      		IF @cumQty <= @ItmBal  --current record isnt sufficient, use it and move on      		BEGIN         		UPDATE StockValuation SET avgPrice = @itmVal / NULLIF(@itmBal, 0);         		SET @itmVal = (@QtySupBal * @Price) + @itmVal	      		END      		ELSE      		BEGIN         		UPDATE StockValuation SET avgPrice = @itmVal / NULLIF(@itmBal, 0);    		SET @itmVal = ((@itmBal - (@cumQty - @QtySupBal)) * @Price) + @itmVal      	END      	FETCH NEXT FROM curValuation INTO @ItemID, @Date1, @QtySupBal, @Price, @AvgPrice   END   CLOSE curValuation   DEALLOCATE curValuation   FETCH NEXT FROM curAvgPrice INTO @ItemIDX, @AvgPriceXENDCLOSE curAvgPriceDEALLOCATE curAvgPrice  | 
                                         
                                        
                                            | 
                                         
                                       
                                     | 
                                   
                            
                       
                          
                            
                                    | 
                                     folumike 
                                    Starting Member 
                                     
                                    
                                    24 Posts  | 
                                    
                                      
                                        
                                          
                                           
                                            Posted - 2013-12-19 : 16:21:59
                                          
  | 
                                         
                                        
                                          quote: Originally posted by visakh16 Learn how to post a question with proper data and output. Without that its difficult to understand what your exact reuqirements arehttp://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs
  Am very sorry. See the detail. Please helpThe aim is to calculate Average Price(AvgPrice) of the stock valuation using two tables:ArrayUnion and StockBalance.AvgPrice = itemValue / itemBalanceitemValue is got by iterating through ArrayUnion table as per selected date.itemBalance is got from StockBalance tablecumQty is the cummulative quantity of the arrayunion table as per the selected ItemID AND dateI expected a Output like this, but not exactlyItemID	AvgPrice1	61702	6754.023	8765.344	2052.735	7078.136	5283.06...But am gettingItemID	AvgPrice1	NULL2	NULL3	NULL4	NULL5	NULL6	NULL...See the script belowif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ArrayUnion]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[ArrayUnion]GOif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StockBalance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[StockBalance]GOCREATE TABLE [dbo].[ArrayUnion] (	[ItemX] [int] IDENTITY(1,1) NULL ,	[IemID] [int] NULL ,	[Date1] [datetime] NULL ,	[QtySupBal] [float] NULL ,	[InvID] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,	[Price] [money] NULL ) ON [PRIMARY]GOCREATE TABLE [dbo].[StockBalance] (	[ItemID] [int] NULL ,	[ItemBal] [float] NULL ) ON [PRIMARY]GOINSERT ArrayUnion VALUES(1,1,'01/01/2013','BEGBAL',6192.52)INSERT ArrayUnion VALUES(2,2,'01/01/2013','BEGBAL',6766.8)INSERT ArrayUnion VALUES(3,2,'02/01/2013','95422569',6766.8)INSERT ArrayUnion VALUES(4,2,'02/01/2013','95422100',6792.8)INSERT ArrayUnion VALUES(5,3,'03/01/2013','BEGBAL',9571.52)INSERT ArrayUnion VALUES(6,3,'05/01/2013','BEGBAL',6192.58)INSERT ArrayUnion VALUES(7,3,'05/01/2013','6900019885',9792.52)INSERT ArrayUnion VALUES(8,4,'06/01/2013','BEGBAL',2182.22)INSERT ArrayUnion VALUES(9,5,'07/01/2013','BEGBAL',7194.52)INSERT ArrayUnion VALUES(10,6,'08/01/2013','BEGBAL',5430.89)INSERT ArrayUnion VALUES(11,6,'14/01/2013','95422588',5430.89)INSERT StockBalance VALUES(1,3277)INSERT StockBalance VALUES(2,4554)INSERT StockBalance VALUES(3,6785)INSERT StockBalance VALUES(4,1824)INSERT StockBalance VALUES(5,5993)INSERT StockBalance VALUES(6,2792)CREATE TABLE StockValuation(ItemID NVARCHAR(100),AvgPrice MONEY)INSERT INTO StockValuation(ItemID, AvgPrice)SELECT DISTINCT ItemID, NULLFROM ArrayUnionORDER BY ItemID/* declare the local variables */DECLARE @ItemIDX NVARCHAR(100), @AvgPriceX MONEYDECLARE @itmBal FLOAT(8), @itmVal FLOAT(8), @cumQty FLOAT(8)DECLARE @ItemID NVARCHAR(100), @Date1 DATETIME, @QtySupBal FLOAT(8), @Price MONEY--SET @AvgPrice = 0SET @cumQty = 0SET @itmBal = (SELECT ItemBal FROM StockBalance)DECLARE curAvgPrice CURSOR FAST_FORWARD FORSELECT ItemID, AvgPriceFROM StockValuationORDER BY ItemIDOPEN curAvgPrice/* This is executed as long as the previous fetch succeeds. */FETCH NEXT FROM curAvgPrice INTO @ItemIDX, @AvgPriceXWHILE (@@FETCH_STATUS = 0)	-- whilst all is wellBEGIN	UPDATE StockValuation SET avgPrice = @itmVal / NULLIF(@itmBal, 0);	DECLARE curValuation CURSOR FAST_FORWARD FOR	SELECT  ItemID, Date1, QtySupBal, Price, AvgPrice	FROM ArrayUnion	ORDER BY ItemID, Date1	OPEN curValuation	-- This is executed as long as the previous fetch succeeds.	FETCH NEXT FROM curValuation INTO @ItemID, @Date1, @QtySupBal, @Price, @AvgPrice   	WHILE (@@FETCH_STATUS = 0) AND (@cumQty <= @itmBal) --whilst all is well & Cummulative Qty = Total Qty as at selected Date	BEGIN      		SET @cumQty = @cumQty + @QtySupBal      		IF @cumQty <= @ItmBal  --current record isnt sufficient, use it and move on      		BEGIN         		UPDATE StockValuation SET avgPrice = @itmVal / NULLIF(@itmBal, 0);         		SET @itmVal = (@QtySupBal * @Price) + @itmVal	      		END      		ELSE      		BEGIN         		UPDATE StockValuation SET avgPrice = @itmVal / NULLIF(@itmBal, 0);    		SET @itmVal = ((@itmBal - (@cumQty - @QtySupBal)) * @Price) + @itmVal      	END      	FETCH NEXT FROM curValuation INTO @ItemID, @Date1, @QtySupBal, @Price, @AvgPrice   END   CLOSE curValuation   DEALLOCATE curValuation   FETCH NEXT FROM curAvgPrice INTO @ItemIDX, @AvgPriceXENDCLOSE curAvgPriceDEALLOCATE curAvgPrice  | 
                                         
                                        
                                            | 
                                         
                                       
                                     | 
                                   
                            
                            
                                | 
                                    
                                      
                                     
                                    
                                 | 
                             
                         
                     | 
                 
             
         |   
     
     
            
              
	     |  
		
			
     
          
		 |