Table with operations:
ID | ID_CUSTOMER | AMOUNT_TRANSFER | ID_ACCOUNT_SENDER | ID_ACCOUNT_RECEIVER|
I have to find ID_CUSTOMER with zero and maximum balance on accounts.
Balance is total difference of all transferred AMOUNT_TRANSFER by accounts.
I tried to find all transfer amounts by customer, but I don't know how find the difference:
SELECT
ACCOUNT.ID, SUM(O.AMOUNT_TRANSFER),
C2.SECOND_NAME AS Фамилия, C2.FIRST_NAME
FROM
ACCOUNT
JOIN
CUSTOMER C2 on ACCOUNT.ID_CUSTOMER = C2.ID
JOIN
OPERATION O on ACCOUNT.ID = O.ID_ACCOUNT_RECEIVER
GROUP BY
ACCOUNT.ID, C2.SECOND_NAME, C2.FIRST_NAME
Example data:
ID ID_CUSTOMER AMOUNT_TRANSFER ID_ACCOUNT_SENDER ID_ACCOUNT_RECEIVER
1 1 5000 1 2
2 2 3000 1 2
3 1 2000 1 2
4 3 2000 2 3
5 3 1000 3 2
then for example,
ID_ACCOUNT == 2 have 5000 + 3000 + 2000 + 1000 are received and 2000 are sended , total balance is 11000 - 2000 = 9000,
next I need balance of all accounts (by account) next I will can calculate balance by customer (just JOIN and SUM) and account with 0 and max (by the same approach)