我有一个SQL表,其中包含以下列:发票ID,债务人ID,发票日期和发票金额。发票ID是唯一的。
我正在尝试创建一个具有平均发票金额的额外列。因此,我希望每行要债务人的平均发票金额,但只需要发票日期<=列的发票日期的发票。
我不确定从哪里开始,欢迎所有想法
答案 0 :(得分:0)
尝试一下-
SELECT
A.Invoice_ID,
A.debtor_ID,
A.invoice_date,
A.invoice_amount,
(
SELECT AVG(B.invoice_amount)
FROM your_table B
WHERE B.debtor_ID = A.debtor_ID
AND B.invoice_date <= A.invoice_date
) AS average_invoice_amount
FROM your_table A
答案 1 :(得分:0)
You want to use window functions:
select t.*,
avg(invoice_amount) over (partition by debtor_id order by invoice_date) as running_average
from t;
I strongly recommend this over a correlated subquery because it should be much faster -- even if you attempt to optimize the correlated subquery with indexes.