C'est un énorme monstre, il va dans un SP donc les variables sont utilisables :
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
Voici ce qu'il fait. Il visite tous les locataires et obtient ce qu'ils ont payé ce mois-ci, et tout ce qu'ils doivent. Il calcule ensuite ce qui est payé pour les charges précédentes, ce mois-ci et les charges futures. Il les additionne ensuite en fonction de la description de la charge et du nom du propriétaire.
Cela a l'air horrible, et je veux savoir s'il y a des raccourcis que je manque et qui pourraient être utilisés.