Running total with monthly fee and discount

Aug. 26, 2021

Posted in:

SELECT SUM(amount) + 5 * (SELECT COALESCE(
	(SELECT COUNT(*) OVER () FROM transactions 
	WHERE amount < 0
	GROUP BY DATE_TRUNC('month', date)
	HAVING ABS(SUM(amount)) > 100 and COUNT(amount) > 2),
    0)) - 5*12 as balance 
FROM transactions;

Tags

Return to blog