如何在Access中使用sql查询减去同一列中的两行值?

时间:2019-05-05 14:32:01

标签: sql ms-access

(查询访问权限)

这是表结构:

+-----+--------+--------+
| id  |  name  |  sub1  |
+-----+--------+--------+
|  1  |  ABC   |  6.27% |
|  2  |  ABC   |  7.47% |
|  3  |  PQR   |  3.39% |
|  4  |  PQR   |  2.21% |
+-----+--------+--------+

我要减去Sub1

输出应为:

+-----+--------+---------+------------------------------------+
| id  |  name  |  sub1   |                                    |
+-----+--------+---------+------------------------------------+
|  1  |  ABC   |  6.27%  |  0      First Rec no need Subtract |
|  2  |  ABC   |  7.47%  |  1.2%   <=(7.47-6.27)              |
|  3  |  PQR   |  3.39%  |  0      First Rec no need Subtract |
|  4  |  PQR   |  2.21%  |  -1.18% <=(2.21-3.39)              |
+-----+--------+---------+------------------------------------+

非常感谢您。

2 个答案:

答案 0 :(得分:0)

这很痛苦,但是您可以这样做:

select t.*,
       (select top 1 t2.sub1
        from t as t2
        where t2.name = t.name and t2.id < t.id
        order by t2.id desc
       ) as prev_sub1
from t;

这将为第一行提供先前的值或NULL。您可以只使用-进行减法。

(name, id)上建立索引将对性能有所帮助。但是,如果可以升级到更好的数据库,则可以只使用lag()

答案 1 :(得分:0)

如果您可以保证连续的id值,那么以下是替代方法:

select t.*, nz(t.sub1-u.sub1,0) as sub2
from YourTable t left join YourTable u on t.name = u.name and t.id = u.id+1

YourTable更改为表格名称。