我有以下架构
Invoices
=================
invoice_number
account_id
invoice_amount
invoice_date
status ("Paid","Not Paid")
我正在尝试编写查询以获取包含以下信息的所有发票......
我遇到了最后一项(最后付款发票金额)的问题。到目前为止,我有......
select
inv2.invoice_number,
inv2.invoice_date,
inv2.account_id,
inv2.invoice_amount,
(
select * from (
select inv.invoice_amount
from invoices inv
where inv.account_id = inv2.account_id
and inv.status = 'PAID'
and inv.invoice_date < inv2.invoice_date
order by inv.invoice_date desc
)
where rownum <=1
) as last_paid_amount
from
invoices inv2
我正在尝试将其重构为不使用相关子查询,因为我的数据集的大小使得这非常昂贵。如何重构使用非相关子查询。这甚至可能吗?
谢谢
答案 0 :(得分:1)
我可能在这里搞砸了order by
条款,因为我现在没有机会测试它,但想法是使用LAG函数:
select
inv2.invoice_number,
inv2.invoice_date,
inv2.account_id,
inv2.invoice_amount,
lag(invoice_amount) over(
partiton by account_id
order by invoice_date, decode(status, 'PAID', 1, 0)
) last_paid_amount
from
invoices inv2
答案 1 :(得分:0)
select a.*, case when rnk = 1 then invoice_amount end as last_paid_amount
from(select
inv2.invoice_number,
inv2.invoice_date,
inv2.account_id,
inv2.invoice_amount,
row_number() over(partition by invoice_number, account_id, (case when status = 'PAID' then 0 else 1 end), invoice_date desc) as rnk
from
invoices inv2) a
顺便说一句,我不确定LAG是否可以在这里工作。