使用基于其他select和SUM的列之一进行选择

时间:2015-06-24 14:52:37

标签: sql hyperfilesql

我正在使用数据库hyperfile client / serveur与windev 17合作。

我有一个名为Operation with colums(accountNumber,date,amount,operationType)的表。

operationType可以采用两个值:“付款”和“取款”。

我想选择帐户中完成的操作列表,我的列表应显示5个列:日期,帐号,金额,操作类型和余额。

最后一栏(余额)应该是当前日期之前完成的所有操作与“付款”类型之间的差额,以及当前日期之前完成的所有操作与“撤销”类型之间的差额

我尝试以下sql代码

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)

但查询不会显示任何值。

我也试过这个

 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

但是我收到错误,告诉我列dateop不存在。

我需要帮助

1 个答案:

答案 0 :(得分:0)

你去找我的男人。

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