Access 中按识别因素分组的连续平均值

Consecutive averages in Access grouped by identifying factors

我在访问数据库中有一个 table,其中包含以下字段:“Period”(如 YYYYMM,例如 202111、202112、202201 等)、ID('short text field' 标识符)、仪器(描述仪器 ID 密钥的 'short text field'),最后是美元金额作为字段“交易量余额”。显然,在现实中,有更多的 ID 和不同的乐器键,而不仅仅是 3 个。 2、如下图所示。现在的目标是计算每个 ID 和每个仪器每连续两个月的简单平均值,例如底部 table(示例数字,单位为美元)。也就是说,一个ID在同一个月可以有多个不同Instrument key的条目(下面table,ID 1和3在两个不同的instrument A和B中有余额,而ID 2只有一个余额在工具 B 中)。

输入-->

Period ID Instrument Volume Balance
202101 1 A 1
202101 2 B 2
202101 3 A 3
202102 1 A 4
202102 1 B 5
202102 2 B 6
202102 3 A 7
202103 1 A 8
202103 2 B 9
202103 3 A 10
202103 3 B 11

期望的结果(本质上是一个迷人的枢轴table)-->

Period ID Instrument Average Volume Balance Comment
202101 1 A 0.5 (Jan balance / 2) since no prior data point for Instrument & ID combination
202101 2 B 1 (Jan balance / 2) since no prior data point for Instrument & ID combination
202101 3 A 1.5 (Jan balance / 2) since no prior data point for Instrument & ID combination
202102 1 A 2.5 (Jan + Feb balance for this specific ID & Instrument combo / 2)
202102 1 B 2.5 (Feb balance / 2) since no prior data point for Instrument & ID combination
202102 2 B 4 (Jan + Feb balance for this specific ID & Instrument combo / 2)
202102 3 A 5 (Jan + Feb balance for this specific ID & Instrument combo / 2)
202103 1 A 6 (Feb + Mar balance for this specific ID & Instrument combo / 2)
202103 2 B 7.5 (Jan + Feb balance for this specific ID & Instrument combo / 2)
202103 3 A 8.5 (Jan + Feb balance for this specific ID & Instrument combo / 2)
202103 3 B 5.5 (Mar balance / 2) since no prior data point for Instrument & ID combination

我玩过 DAvg 函数,但连续的周期截止和分组对我来说是致命的。感谢您的帮助!

使用自己 ​​LEFT 加入:

SELECT t1.*,
       (t1.[Volume Balance] + Nz(t2.[Volume Balance])) / 2 AS [Average Volume Balance]
FROM (
  SELECT * FROM tablename
  UNION ALL
  SELECT Format(DateAdd('m', 1, CDate(Format(MAX(Period) + '01', '0000-00-00'))), 'yyyymm'), ID, Instrument, 0
  FROM tablename
  GROUP BY ID, Instrument
) AS t1 LEFT JOIN tablename AS t2
ON DateAdd('m', 1, CDate(Format(t2.Period + '01', '0000-00-00'))) = CDate(Format(t1.Period + '01', '0000-00-00'))
AND t2.ID = t1.ID AND t2.Instrument = t1.Instrument
ORDER BY t1.ID, t1.Instrument, t1.Period;