我正在使用数据库hyperfile client / serveur与windev合作。
我有一个名为Operation with colums(accountNumber,date,amount,operationType)的表。
operationType可以采用两个值:“付款”和“取款”。
我想选择帐户中完成的操作列表,我的列表应显示5个列: 日期,帐户编号,金额,操作类型和余额。
最后一栏(余额)应该是当前日期之前完成的所有操作与“付款”类型之间的差额,以及当前日期之前完成的所有操作与“撤销”类型之间的差额
我尝试以下sql代码
SELECT accountNumber, date as dateOpe, amount, operationType, (SUM (SELECT Operation.amount
FROM Operation
WHERE Operation.date<=dateOpe AND Operation.operationType='payment')
-SUM (SELECT Operation.amount
FROM Operation
WHERE Operation.date<=dateOpe AND Operation.operationType='withdrawal')) as balance
FROM Operation
但我总是有一个错误告诉我,我没有权利在SUM
中添加一个选择请有人帮助我。如何编写这样的SQL查询。
提前致谢
答案 0 :(得分:0)
请试试这个:
SELECT accountNumber, date, amount, operationType,
(SELECT SUM(amount) AS balance
FROM operation WHERE operationType='payment' and date=date)
-(SELECT SUM(amount) AS balance
FROM operation WHERE operationType='withdrawal' and date=date)
as balance
FROM operation
答案 1 :(得分:0)
尝试使用子查询查找SUM,如下所示。可能有更优雅的解决方案,但这应该有效。
SELECT date, accountNumber,
operationType, deposits - withdrawals AS balance
FROM Operations o INNER JOIN (
SELECT accountNumber, SUM(amount) AS withdrawals
FROM Operaions
WHERE operationType = 'withdrawal'
GROUP BY accountNumber
) a ON o.accountNumber = a.accountNumber
INNER JOIN (
SELECT accountNumber, SUM(amount) AS deposits
FROM Operations
WHERE operationType = 'deposit'
GROUP BY accountNumber
)b ON o.accountNumber = b.accountNumber
答案 2 :(得分:0)
我会使用逻辑表达式,如果为false则为0,如果为true,则为1。因此,如果表达式为假,Operation.amount * <logical expression>
将产生0,如果表达式为真,则Operation.amount
将产生 SELECT accountNumber, date as dateOpe, amount, operationType,
SUM (Operation.amount * (Operation.date<=dateOpe AND Operation.operationType='payment')) -
SUM (Operation.amount * (Operation.date<=dateOpe AND Operation.operationType='withdrawal')) as balance
FROM Operation
。因此,以下查询应该接近解决方案(未经测试):
std::thread