【发布时间】:2021-12-11 11:45:33
【问题描述】:
我需要根据事务板生成一个老化报告,即在 2、5、10 等间隔上。用户将选择报告开始日期和结束日期,然后我们需要为该特定日期范围生成报告。报告应采用这样的方式,即交易应分成多个板块;例如 0-2、3-4、5-6、6-8 和大于 8 天。我为每个平板编写了一个子查询,它给了我所需的数据。但是由于数据每天都在增加,因此需要花费太多时间。我也尝试了索引,但它并没有提高性能。
select id_ledger as ledger_id,
customer_id,
title as ledger,
(
select COALESCE((sum(dr_amount) - sum(clearance_amount)), 0) as diff_value
from journal_voucher_details
where cr_amount = 0
and (('2021-10-23' - transaction_date) <= (2))
and ledger_id = l.customer_id
and transaction_date >= '2021-10-01'
and transaction_date <= '2021-10-24'
group by ledger_id
) as slab1,
(
select COALESCE((sum(dr_amount) - sum(clearance_amount)), 0) as diff_value
from journal_voucher_details
where cr_amount = 0
and (('2021-10-23' - transaction_date) <= (2 * 2))
and (('2021-10-23' - transaction_date) > (2 * 1))
and ledger_id = l.customer_id
and transaction_date >= '2021-10-01'
and transaction_date <= '2021-10-24'
group by ledger_id
) as slab2,
(
select COALESCE((sum(dr_amount) - sum(clearance_amount)), 0) as diff_value
from journal_voucher_details
where cr_amount = 0
and (('2021-10-23' - transaction_date) <= (2 * 3))
and (('2021-10-23' - transaction_date) > (2 * 2))
and ledger_id = l.customer_id
and transaction_date >= '2021-10-01'
and transaction_date <= '2021-10-24'
group by ledger_id
) as slab3,
(
select COALESCE((sum(dr_amount) - sum(clearance_amount)), 0) as diff_value
from journal_voucher_details
where cr_amount = 0
and (('2021-10-23' - transaction_date) <= (2 * 4))
and (('2021-10-23' - transaction_date) > (2 * 3))
and ledger_id = l.customer_id
and transaction_date >= '2021-10-01'
and transaction_date <= '2021-10-24'
group by ledger_id
) as slab4,
(
select COALESCE((sum(dr_amount) - sum(clearance_amount)), 0) as diff_value
from journal_voucher_details
where cr_amount = 0
and (('2021-10-23' - transaction_date) > (2 * 4))
and ledger_id = l.customer_id
and transaction_date >= '2021-10-01'
and transaction_date <= '2021-10-24'
group by ledger_id
) as slab5,
(
select COALESCE((sum(dr_amount) - sum(clearance_amount)), 0) as diff_value
from journal_voucher_details
where cr_amount = 0
and 1 = 1
and ledger_id = l.customer_id
and transaction_date >= '2021-10-01'
and transaction_date <= '2021-10-24'
group by ledger_id
) as balance
from ledgers l;
注意: 2021-10-1 ==> 开始日期
2021-10-24 ==> 结束日期
2021-10-23 ==> 报告日期
选择2作为板号。
如何提高此查询的性能?
提前致谢。
【问题讨论】:
标签: sql postgresql query-optimization