同一列中值的差异 ms access sql (mdb)

Difference of values in the same column ms access sql (mdb)

我有一个 table,其中包含两个值不唯一的列,这些值是自动生成的,我对此无能为力,无法编辑 table,数据库也不制作自定义功能。

考虑到这一点,我已经在 sql 服务器中解决了这个问题,但它包含一些 ms-access 中不存在的功能。

列是 Volume 和 ComponentID,这是我在 sql 中的代码:

with rows as (
                 select row_number() over (order by volume) as rownum, volume
                from   test where componentid = 'S3')
 
select top 10
       rowsMinusOne.volume, coalesce(rowsMinusOne.volume - rows.volume,0) as diff
from   rows as rowsMinusOne
                left outer join rows
                       on rows.rownum = rowsMinusOne.rownum - 1

示例数据:

58.29168 
70.57396
85.67902
97.04888
107.7026
108.2022
108.3975
108.5777
109
109.8944

预期结果:

Volume diff
58.29168 0
70.57396 12.28228
85.67902 15.10506
97.04888 11.36986
107.7026 10.65368
108.2022 0.4996719
108.3975 0.1952896
108.5777 0.1801834
109 0.4223404
109.8944 0.89431

我已经通过用 NZ 替换它来解决合并的部分,我尝试使用 DCOUNT 来解决 row_number (How to show the record number in a MS Access report table?) 但我收到它找不到的错误函数(我正在通过代码读取数据,这是我唯一能做的)。

我也试过了,但是,正如答案所说,我需要一个具有唯一值的列,我没有也不能创建

考虑:

SELECT TOP 10 Table1.ComponentID, 
DCount("*","Table1","ComponentID = 'S3' AND Volume<" & [Volume])+1 AS Seq, Table1.Volume, 
Nz(Table1.Volume -
    (SELECT Top 1 Dup.Volume FROM Table1 AS Dup 
     WHERE Dup.ComponentID = Table1.ComponentID AND Dup.Volume<Table1.Volume 
     ORDER BY Volume DESC),0) AS Diff
FROM Table1
WHERE (((Table1.ComponentID)="S3"))
ORDER BY Table1.Volume;

对于大型数据集,这可能会执行得非常慢。

替代解决方案:

  1. 构建计算差异的查询,使用该查询作为报告源,使用文本框 RunningSum 属性 计算序列号

  2. VBA 遍历记录集并将结果保存到 'temp' table

  3. 导出到 Excel