-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy path07_PaidDate.sql
More file actions
59 lines (48 loc) · 1.55 KB
/
07_PaidDate.sql
File metadata and controls
59 lines (48 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
UPDATE i
SET PaidDate =
CASE
-- Fully settled via payment and/or credit
WHEN s.PaidLocal + s.CreditedLocal >= s.AmountLocal
THEN
CASE
WHEN s.LastPaymentDate IS NOT NULL
AND s.LastCreditDate IS NOT NULL
THEN
CASE
WHEN s.LastPaymentDate > s.LastCreditDate
THEN s.LastPaymentDate
ELSE s.LastCreditDate
END
ELSE COALESCE(s.LastPaymentDate, s.LastCreditDate)
END
-- Written off
WHEN s.WriteOffDate IS NOT NULL
THEN s.WriteOffDate
-- Otherwise still open
ELSE NULL
END
FROM Invoice i
JOIN
(
SELECT
i.InvoiceID
, i.AmountLocal
, SUM(ISNULL(pa.AppliedLocal,0)) AS PaidLocal
, SUM(ISNULL(c.AmountLocal,0)) AS CreditedLocal
, MAX(p.PaymentDate) AS LastPaymentDate
, MAX(c.CreditDate) AS LastCreditDate
, MAX(b.WriteOffDate) AS WriteOffDate
FROM Invoice i
LEFT JOIN PaymentAllocation pa
ON pa.InvoiceID = i.InvoiceID
LEFT JOIN Payment p
ON p.PaymentID = pa.PaymentID
LEFT JOIN CreditNote c
ON c.InvoiceID = i.InvoiceID
LEFT JOIN BadDebt b
ON b.InvoiceID = i.InvoiceID
GROUP BY
i.InvoiceID
, i.AmountLocal
) s
ON s.InvoiceID = i.InvoiceID;