[英]Make a select with one of the column based on other select
我正在使用數據庫超文件客戶端/服務器的windev。
我有一個名為Operation的表,帶有colums(accountNumber,日期,金額,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查詢。
提前致謝
請嘗試以下方法:
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
嘗試使用子查詢來查找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
我會使用這樣的事實:如果為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.