我需要一些代码来计算从收据1开始的行基数的当前平均值。
我有下表,其中包含采购数量,价格等数据。我需要计算从收货开始的每一行的运行平均值(当前平均值)。收货一个总是很容易,因为之前的价格不会影响它的平均值。
一旦你收到平均收入(75英镑),就可以用它来计算后续行。
我手动计算收据2为“£79.4858”。我被告知使用CTE递归的最佳方式。
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))),
(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))),
(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 :(得分:1)
只需使用累计平均值:
select x.*,
avg(?) over (order by [Item No_]) as running_avg
from dbo.x;
?
适用于您关注的列。我无法告诉你想要的平均值。
答案 1 :(得分:1)
它应该是这样的:
SELECT *
,AVG([IntakeSellingPrice]) OVER (ORDER BY [Item No_] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM [dbo].[X]
使用OVER子句和ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
将对从开始行到当前行的所有列执行聚合,其中行按ORDER BY
子句排序。
答案 2 :(得分:1)
我不确定你是否正在寻找像lag()
函数
select [Item No_],ReceiptNo,((PurchaseQty * IntakeSellingPrice) +
(InventoryBalance * isnull(lag(IntakeSellingPrice) over (order by [Item No_]), IntakeSellingPrice)
))/NewBalance [RunningAVG]
from X
结果:
Item No_ ReceiptNo RunningAVG
2000045 1 75.000000
2000045 2 79.485808
2000045 3 80.000000