我有下表,其中包含购买数量,价格等数据。我需要计算每一行的运行平均值(当前平均值)。
收据1的第一个当前平均值是75英镑,因为500个单位是以75英镑购买的。没有以前的单位,所以第一个单位是用(PurchaseQty * IntakeSellingPrice)/ IntakeSellingPrice = CurrentAvg
计算的我已使用以下方法手动计算收据2到“£79.4858”:
* 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)))
答案 0 :(得分:0)
您可以将每一行与运行平均值之前的所有其他行相连,然后找到按前一行分组的平均值。因此,假设没有2行相同,这将起作用:
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]