Make a select with one of the column based on other select and SUM

372 views Asked by At

I'm working with windev 17 using the database hyperfile client/serveur.

I have a table named Operation with colums (accountNumber, date, amount, operationType ).

operationType can take two values: "payment" and "withdrawal".

I want to select the List of operations done in an account and, my List should display 5 colums: Date, accountNumber, amount, operationType and balance.

The last column (balance) should be the difference between the sum of all operations done before the current date with type "payment" and the sum of all operation done before the current date with type "withdrawal"

I try the following sql code

SELECT date, accountNumber, operationType, deposits - withdrawals AS balance
FROM Operations o INNER JOIN (
     SELECT accountNumber, date, SUM(amount) AS withdrawals
     FROM Operaions
     WHERE operationType = 'withdrawal'
     GROUP BY accountNumber
) a ON  (o.accountNumber = a.accountNumber AND a.date<=o.date)
INNER JOIN (
     SELECT accountNumber,date, SUM(amount) AS deposits
     FROM Operations
     WHERE operationType = 'deposit'
     GROUP BY accountNumber
)b ON (o.accountNumber = b.accountNumber AND b.date<=o.date)

but the Query does'nt display any value.

I also tried this one

 SELECT date as dateop, accountNumber, operationType, deposits - withdrawals AS balance
FROM Operations o INNER JOIN (
     SELECT accountNumber, date, SUM(amount) AS withdrawals
     FROM Operaions
     WHERE operationType = 'withdrawal' AND date<=dateop
     GROUP BY accountNumber
) a ON  o.accountNumber = a.accountNumber
INNER JOIN (
     SELECT accountNumber,date, SUM(amount) AS deposits
     FROM Operations
     WHERE operationType = 'deposit' AND date<=dateop
     GROUP BY accountNumber
)b ON o.accountNumber = b.accountNumber

but i'm getting an error telling me that column dateop does not exist.

please i need a help

1

There are 1 answers

0
Philip Devine On

Here you go my man.

select accountNumber, dateField, sum(isnull(deposits,0)) - sum(isnull(withdrawals,0)) from (
select accountNumber, operationType, dateField, 
case when operationType = 'deposit' then sum(sum(amount)) over (partition by accountNumber, operationType order by dateField asc) else null end deposits,
case when operationType = 'withdrawal' then sum(sum(amount)) over (partition by accountNumber, operationType order by dateField asc) else null end withdrawals
from operations a
group by accountNumber, operationType, dateField
) a group by accountNumber, dateField