简体   繁体   中英

SQL Calculate Running average

I have the below table which contains data for purchase quantity, price etc. I need to calculate the running average (current average) for each row.

The first currentAverage Value for receipt 1 is £75 because 500 units were purchased at £75. there were no previous units so the first one is calculated with (PurchaseQty * IntakeSellingPrice) / IntakeSellingPrice = CurrentAvg

I have manually calculated receipt 2 to by "£79.4858" using the following method:

*select *, ((PurchaseQty * IntakeSellingPrice) + (InventoryBalance * )) / NewBalance [CurrentAVG]*

CREATE TABLE [dbo].[X](
[Item No_] [nvarchar](20) NOT NULL,
[ReceiptNo] [bigint] NULL,
[Sold] [decimal](38, 20) NULL,
[InventoryBalance] [decimal](38, 20) NOT NULL,
[PurchaseQty] [decimal](38, 20) NULL,
[IntakeSellingPrice] [decimal](38, 20) NULL,
[NewBalance] [decimal](38, 20) NULL,
[CurrentAverage] [numeric](2, 2) NOT NULL
) ON [PRIMARY]
GO

INSERT [dbo].[X] ([Item No_], [ReceiptNo], [Sold], [InventoryBalance], [PurchaseQty], [IntakeSellingPrice], [NewBalance], [CurrentAverage]) VALUES (N'2000045', 1, CAST(0.00000000000000000000 AS Decimal(38, 20)), CAST(0.00000000000000000000 AS Decimal(38, 20)), CAST(500.00000000000000000000 AS Decimal(38, 20)), CAST(75.00000000000000000000 AS Decimal(38, 20)), CAST(500.00000000000000000000 AS Decimal(38, 20)), CAST(0.00 AS Numeric(2, 2))) GO
INSERT [dbo].[X] ([Item No_], [ReceiptNo], [Sold], [InventoryBalance], [PurchaseQty], [IntakeSellingPrice], [NewBalance], [CurrentAverage]) VALUES (N'2000045', 2, CAST(250.00000000000000000000 AS Decimal(38, 20)), CAST(250.00000000000000000000 AS Decimal(38, 20)), CAST(2181.00000000000000000000 AS Decimal(38, 20)), CAST(80.00000000000000000000 AS Decimal(38, 20)), CAST(2431.00000000000000000000 AS Decimal(38, 20)), CAST(0.00 AS Numeric(2, 2))) GO
INSERT [dbo].[X] ([Item No_], [ReceiptNo], [Sold], [InventoryBalance], [PurchaseQty], [IntakeSellingPrice], [NewBalance], [CurrentAverage]) VALUES (N'2000045', 3, CAST(316.00000000000000000000 AS Decimal(38, 20)), CAST(2115.00000000000000000000 AS Decimal(38, 20)), CAST(10.00000000000000000000 AS Decimal(38, 20)), CAST(80.00000000000000000000 AS Decimal(38, 20)), CAST(2125.00000000000000000000 AS Decimal(38, 20)), CAST(0.00 AS Numeric(2, 2)))

You can join each row with all other rows that come before it in the running average, and then find their average grouped by the former row. So, assuming that no 2 rows are the same, this will work:

SELECT a.*, AVG(b.CurrentAverage) 
FROM dbo.X a INNER JOIN dbo.X b
ON a.[Item No_] >= b.[Item No_] --or whatever you are ordering your records by for the running average
GROUP BY a.[Item No_], ..., a.[CurrentAverage]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM