如何计算Oracle查询中每个trans_date的期末余额?

时间:2018-09-23 20:46:41

标签: sql oracle oracle11g

  1. 在这里,我想每个var studentSheet = spreadsheet.getSheetByName('student'); var sourceSheet = spreadsheet.getSheetByName('Sheet6'); // copyTo rows sourceSheet.getRange(2, 5).copyTo(studentSheet.getRange(3, 1), {contentsOnly: true}); ... SpreadsheetApp.flush(); // applies all values to the student spreadsheet // and therefore all the formula cells update // get value from calculated formula cell studentSheet.getRange(2, 22).copyTo(sourceSheet.getRange(2, 6), {contentsOnly: true}); 的期末余额,以便与trans_date关联的期末余额成为我当月的期末余额。
  2. 样本表:

last_trans_date

我使用以下查询:

TRANS_DAT     CREDIT      DEBIT
--------- ---------- ----------
24-SEP-18       2500        400
24-SEP-18                   200
24-SEP-18        500
30-SEP-18        400       1200
30-SEP-18        400

输出:

SELECT TRANS_DATE, SUM(NVL(CREDIT,0)-NVL(DEBIT,0)) BALANCE  
  FROM BANK_TRANS GROUP BY TRANS_DATE;

TRANS_DATE BALANCE --------- ---------- 24-SEP-18 2400 30-SEP-18 -400 的期末余额应为30-SEP-18,作为正确的月末期末余额,但我仅获得该天的期末余额。

请帮助我。

1 个答案:

答案 0 :(得分:0)

如果按每个日期分组,则每个日期将获得一行。如果您使用trunc() function,则可以每月获取行和值:

SELECT trunc(TRANS_DATE,'MONTH'), SUM(NVL(CREDIT,0)-NVL(DEBIT,0)) BALANCE 
FROM BANK_TRANS 
GROUP BY trunc(TRANS_DATE,'MONTH');