簡體   English   中英

使用其他select和SUM基於該列之一進行選擇

[英]Make a select with one of the column based on other select and SUM

我正在使用數據庫超文件客戶端/服務器處理windev 17。

我有一個名為Operation的表,帶有colums(accountNumber,日期,金額,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不存在。

請我需要幫助

在這里,你走我的男人。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM