0

我正在使用数据库超文件客户端/服务器与windev一起工作。

我有一个名为 Operation 的表,其中包含列(accountNumber、date、amount、operationType)。

operationType 可以取两个值:“payment”和“withdrawal”。

我想选择一个帐户中完成的操作列表,我的列表应该显示 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 查询。

提前致谢

4

3 回答 3

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
于 2015-06-23T18:35:38.003 回答
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
于 2015-06-23T18:39:15.180 回答
0

我会使用这样一个事实,即逻辑表达式如果为假则产生 0,如果为真则产生 1。因此,Operation.amount * <logical expression>如果表达式为假且Operation.amount表达式为真,则将产生 0。因此,以下查询应该接近解决方案(未经测试):

        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
于 2015-06-23T18:51:14.720 回答