Problem: I have a SQL Server table as follows:
transaction id | timestamp | customer | cost | operation |
---|---|---|---|---|
123 | 10-12-2020 | 1 | 60 | credit |
456 | 11-12-2020 | 2 | 50 | credit |
789 | 11-12-2020 | 1 | 20 | debit |
000 | 12-12-2020 | 3 | 100 | credit |
999 | 15-12-2020 | 2 | 50 | debit |
I want to have an overall real-time balance of the customer as shown below. So that before entering a new record in the above transaction table I will check the balance for that customer and show it to the user.
customer | balance |
---|---|
1 | 40 |
2 | 0 |
3 | 100 |
I tried joins and consolidation but those did not work.
You can just use conditional aggregation:
select customer,
sum(case when operation = 'credit' then cost else -cost end) as balance
from mytable
group by customer
The case
expression in the sum()
adds or substracts the cost depending if it's a credit or a debit.
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.