假设我们有如下的日记账分录表
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:是在给定日期的一年内(从给定日期的 1 月 1 日到当天)与 account_number 相关的所有借记的累计总和。
credit_till_this_day:是在给定日期的一年(从给定日期的 1 月 1 日到当天)与 account_number 相关的所有信用的累计总和。
我试过这个选择:
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
但我正在寻找其他解决方案(可能通过使用分析函数)以获得最佳性能。
最佳答案
我将使用 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()
给出,呃,给定月份的最后一天。
关于sql - 建立会计试算平衡报告绩效问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407196/