2015-06-23 116 views
0

我正在使用windev使用數據庫超文件客戶端/服務器。根據其他選擇的列進行選擇

我有一個名爲操作與colums(accountNumber,日期,金額,操作類型)的表。

operationType可以取兩個值:「payment」和「withdraw」。

我想選擇在一個帳戶中完成的操作列表,我的列表應該顯示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

請試試這個:

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 
0

嘗試類似於以下,使用子查詢找到的款項。可能有一個更優雅的解決方案,但這應該起作用。

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 
+0

好的,感謝您的回覆。 我嘗試這個解決方案,但是,有一些缺乏。 金額總和(SUM(金額))應基於當前操作之前完成的操作。所以INNER JOIN中的日期應該<=當前操作的日期。請問我該怎麼辦? – blaiso

0

我會使用這樣一個事實,即邏輯表達式如果爲false,則返回0,如果爲true,則返回1。因此,如果表達式爲false,Operation.amount * <logical expression>將產生0,如果表達式爲true,則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