This is one huge monster, it's going into a SP so variables are usable:
SELECT OwnerName, SUM(AmountPaid) AS Paid, SUM(AmountOwedComplete) AS Owed, SUM(AmountOwedThisMonth) AS OwedMonth,
SUM(PaidForPast) AS PaidPast, SUM(PaidForPresent) AS PaidPresent, SUM((AmountPaid - PaidForPast - PaidForPresent)) AS PaidFuture, [Description] FROM (
SELECT OwnerName, AmountPaid, AmountOwedComplete, AmountOwedThisMonth, PaidForPast, [Description],
(SELECT CASE WHEN (AmountPaid - PaidForPast) < ABS(AmountOwedThisMonth) THEN AmountPaid - PaidForPast
ELSE ABS(AmountOwedThisMonth) END) AS PaidForPresent
FROM (
SELECT OwnerName, AmountPaid, AmountOwedTotal - AmountPaid AS AmountOwedComplete,
AmountOwedThisMonth,
(SELECT CASE WHEN (AmountPaid < ABS((AmountOwedTotal - AmountPaid)) + AmountOwedThisMonth)
THEN AmountPaid ELSE ABS((AmountOwedTotal - AmountPaid)) + AmountOwedThisMonth END) AS PaidForPast,
Description, TransactionDate
FROM (
SELECT DISTINCT t.TenantName, p.PropertyName, ISNULL(p.OwnerName, 'Uknown') AS OwnerName, (
SELECT SUM(Amount) FROM tblTransaction WHERE
Amount > 0 AND TransactionDate >= @StartDate AND TransactionDate <= @EndDate
AND TenantID = t.ID AND TransactionCode = trans.TransactionCode
) AS AmountPaid, (
SELECT SUM(Amount) FROM tblTransaction WHERE
tblTransaction.TransactionCode = trans.TransactionCode AND tblTransaction.TenantID = t.ID
) AS AmountOwedTotal, (
SELECT SUM(Amount) FROM tblTransaction WHERE tblTransaction.TransactionCode = trans.TransactionCode AND tblTransaction.TenantID = t.ID
AND Amount < 0 AND TransactionDate >= @StartDate AND TransactionDate <= @EndDate
) AS AmountOwedThisMonth, code.Description, trans.TransactionDate FROM tblTransaction trans
LEFT JOIN tblTenantTransCode code ON code.ID = trans.TransactionCode
LEFT JOIN tblTenant t ON t.ID = trans.TenantID
LEFT JOIN tblProperty p ON t.PropertyID = p.ID
WHERE trans.TransactionDate >= @StartDate AND trans.TransactionDate <= @EndDate AND trans.Amount > 0
) q
) q2
)q3
GROUP BY OwnerName, Description
This is what it does. It visits all the Tenants and gets what they have paid for this month, and everything they owe. Then it calculates what is paid for previous charges, this month, and future charges. It then sums them based on Description of the charge, and the Name of the property owner.
It looks horrible, and I want to know if there are some shortcuts I'm missing that could be used.