Quote:
|
But it is hard to say exactly without seeing your DDL.
|
Yes, I agree.
Anyhow, with the information currently available from OP, (and using my guess) I want to try like this:
(I assumed that date_paid IS NULL if not paid.)
Code:
SELECT customer_id AS customer
, AVG(CAST(days(COALESCE(date_paid, current_date))
- days(invoice_date)
AS DEC(7,2) )
) AS "avg. days to pay the invoice"
FROM (SELECT customer_id
, invoice_date
, date_paid
FROM current_invoice
UNION ALL
SELECT customer_id
, invoice_date
, date_paid
FROM past_invoice
) Q
GROUP BY
customer_id
;
Or, this:
Code:
SELECT COALESCE(ci.customer_id, pi.customer_id) AS customer
, AVG(CAST(days(COALESCE(ci.date_paid, pi.date_paid, current_date))
- days(COALESCE(ci.invoice_date, pi.invoice_date))
AS DEC(7,2) )
) AS "avg. days to pay the invoice"
FROM current_invoice ci
FULL OUTER JOIN
past_invoice pi
ON ci.customer_id = pi.customer_id
AND ci.invoice_id = pi.invoice_id
GROUP BY
COALESCE(ci.customer_id, pi.customer_id)
;