简体   繁体   English

SQL:存储列的计算值,并将其用于进一步操作

[英]SQL: Store Calculated value of column and use it for further manipulation

I Have a Table with Id , Gross Amount and Amount Applied . 我有一张表,上面有IdGross Amount和已Amount Applied

ID | Gross Amt | Amt Applied | Outstanding Amount
1  |   100     |    10       |    90
1  |   100     |    10       |    80
1  |   100     |    10       |    70

How to get outstanding Amount value for each column for same id. 如何为相同ID的每一列获取未清金额。

Thanks 谢谢

If I understand correctly, you can use a cumulative sum. 如果我理解正确,则可以使用累计和。 However, that depends on the ordering of the rows. 但是,这取决于行的顺序。 SQL tables represent unordered sets. SQL表表示无序集。 You need a column to specify the ordering. 您需要一列来指定顺序。

Assuming you have such a column, you can use the ANSI-standard function for cumulative sums in most databases: 假设您有这样一列,则可以对大多数数据库中的累积总和使用ANSI标准函数:

select t.*,
       (gross_amount - sum(amt_applied) over (partition by id order by ?)
       ) as outstanding_amount
from t;

The ? ? is for the ordering column. 用于订购栏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM