1

假设我们有如下日记帐分录表

create table jour_entries 
 (jseq number, 
  j_date date, 
  Eseq number, 
  account_no varchar2(32), 
  debit number, 
  credit number,
  note varchar2(256) );

如何在 SQL 中为试算平衡构建最佳性能报告?报告栏是

  • account_number:是帐号。

  • debit_within_month:是与 account_number 相关的所有借方的总和,从给定月份的 1 日到该月月底(如果给定日期在当前月份,则到当前日期)

  • credit_within_month:是与 account_number 相关的所有信用的总和,从给定月份的 1 日到该月月底(如果给定日期是当前月份,则到当前日期)

  • debit_till_this_day:是给定日期一年内与 account_number 相关的所有借方的累计总和(从给定日期的 1 月 1 日开始到当天)。

  • credit_till_this_day:是给定日期一年内与 account_number 相关的所有信用的累计总和(从给定日期的 1 月 1 日开始到当天)。


我试过这个选择:

select account_number
      , debit_within_month
      , credit_within_month
      , debit_till_this_day
      , credit_till_this_day
from jour_entries j, 
    (select account_number, sum(debit) debit_within_month, 
                         sum(credit) credit_within_month
              from jour_entries 
              where j_date between trunc(given_date, 'month') and given_date
              group by account_number
    ) j1,
    (select account_number, sum(debit) debit_till_this_day,
                         sum(credit) credit_till_this_day  
              from jour_entries 
              where j_date between trunc(given_date, 'year') and given_date
              group by account_number
    ) j2
wherer j.account_number = j1.account_number
and j.account_number = j2.account_number

但我正在寻找其他解决方案(也许通过使用分析函数)以获得最佳性能。

4

2 回答 2

2

我将使用 SQL*Plus 替换变量语法来表示 given_month。您需要为您实际使用的任何客户端更改此设置。

select account_number
       , sum ( case when J_date between trunc(&given_date, 'mm') 
                                    and least(sysdate, last_day(&given_date)) 
          then debit else 0 end ) as debit_within_month
       , sum ( case when J_date between trunc(&given_date, 'mm')
                                   and least(sysdate, last_day(&given_date)) 
            then credit else 0 end ) as credit_within_month
       , sum ( case when J_date between trunc(&given_date, 'yyyy') and sysdate)  
               then debit else 0 end ) as debit_til_this_day
      , sum ( case when J_date between trunc(&given_date, 'yyyy') and sysdate)  
              then credit else 0 end ) as credit_til_this_day
from jour_entries
group by account_number

解释

  • trunc()应用于日期会将其截断为给定的格式掩码。所以trunc(sysdate, 'mm')给出了一个月的第一天,'yyyy' 掩码给出了一年的第一天。
  • last_day()给出,呃,给定月份的最后一天。
于 2013-01-18T21:24:31.297 回答
0

如果我理解你的问题,听起来像这样的东西应该适合你:

SELECT JE.Account_no as Account__Number,
    SUM(JE2.debit) as Debit_Within_Month,
    SUM(JE2.credit) as Credit_Within_Month,
    SUM(JE.debit) as Debit_Till_This_Day,
    SUM(JE.credit) as Credit_Till_This_Day
FROM Jour_Entries JE
    LEFT JOIN (
        SELECT jseq, Account_No, Debit, Credit
        FROM Jour_Entries
        WHERE to_char(j_date, 'YYYY') = 2013 AND to_char(j_date, 'mm') = 2
    ) JE2 ON JE.jseq  = JE2.jseq 
WHERE to_char(j_date, 'YYYY') = 2013 
GROUP BY JE.Account_no

这是sql fiddle

祝你好运。

于 2013-01-18T21:09:50.740 回答