Last active
August 29, 2015 14:22
-
-
Save nalanj/81b5e9c11b87ba7d8fcf to your computer and use it in GitHub Desktop.
Invoice Analysis
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 user_id, to_char(date, 'YYYY-MM') AS month, SUM(amount) as total | |
FROM invoices | |
GROUP BY user_id, month | |
ORDER BY user_id, month; |
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 invoices.user_id, | |
to_char(invoices.date, 'YYYY-MM') AS invoices_month, | |
SUM(invoices.amount) AS invoices_amount, | |
SUM(last_month_invoices.amount) AS last_month_amount, | |
SUM(past_months_invoices.amount) AS past_months_amount | |
FROM invoices | |
LEFT JOIN invoices as last_month_invoices | |
ON last_month_invoices.user_id = invoices.user_id | |
AND last_month_invoices.date >= | |
date_trunc('month', invoices.date - '1 month'::interval)::date | |
AND last_month_invoices.date <= | |
date_trunc('month', invoices.date)::date - 1 | |
LEFT JOIN invoices as past_months_invoices | |
ON past_months_invoices.user_id = invoices.user_id | |
AND past_months_invoices.date <= | |
date_trunc('month', invoices.date - '1 month'::interval)::date - 1 | |
GROUP BY invoices.user_id, invoices_month | |
ORDER BY invoices_month, invoices.user_id |
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
CREATE TABLE invoices( | |
user_id INTEGER, date DATE, amount INTEGER | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment