Created
September 19, 2013 18:06
-
-
Save nessamurmur/6627481 to your computer and use it in GitHub Desktop.
SQL is NOT DRY.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT people.first_name, | |
people.last_name, | |
SUM(CAST(transactions.amount_in_cents AS float) / 100.00), // total transaction amount all time | |
ytd.amount, | |
transactions.amount_in_cents, // last transaction processed | |
last_transaction.created_at // date of last transaction | |
FROM people | |
JOIN transactions | |
ON people.id = transactions.person_id | |
INNER JOIN (SELECT DISTINCT(transactions.person_id) AS id, | |
SUM(CAST(transactions.amount_in_cents AS float) / 100.00) AS amount | |
FROM transactions | |
WHERE transactions.created_at >= CAST(extract (year FROM current_date) || '-01-01' AS date) | |
GROUP BY transactions.person_id | |
) AS ytd | |
ON people.id = ytd.id | |
LEFT JOIN (SELECT transactions.person_id AS id, | |
MAX(transactions.created_at) AS created_at | |
FROM transactions | |
GROUP BY transactions.person_id | |
) AS last_transaction | |
ON people.id = last_transaction.id | |
WHERE transactions.created_at = last_transaction.created_at | |
GROUP BY people.id, ytd.amount, last_transaction.created_at, transactions.created_at, transactions.amount_in_cents | |
ORDER BY people.last_name, people.first_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment