简体   繁体   中英

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

I Have a Table with Id , Gross Amount and 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.

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. 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:

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

The ? is for the ordering column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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