Created
March 4, 2012 01:41
-
-
Save peterkeen/1969827 to your computer and use it in GitHub Desktop.
Complicated ledger query
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
-- Count the number of months where the 12 month moving average of after-tax expenses excluding travel (basically, normal ordinary expenses) went up, down, or didn't change | |
select | |
sum(case when pct_change > 0 then 1 else 0 end) as up, | |
sum(case when pct_change < 0 then 1 else 0 end) as down, | |
sum(case when pct_change = 0 then 1 else 0 end) as no_change | |
from ( | |
select | |
xtn_month, | |
((expenses - prev) / prev) * 100 as pct_change | |
from ( | |
select | |
xtn_month, | |
expenses, | |
lag(expenses, 1) over (rows unbounded preceding) as prev | |
from ( | |
select | |
xtn_month, | |
avg(amount) over (rows 12 preceding) as expenses | |
from ( | |
select | |
xtn_month, | |
sum(amount) as amount | |
from | |
ledger | |
where | |
account ~ 'Expenses' | |
and account !~ 'Depreciation' | |
and account !~ 'Taxes' | |
and account !~ 'Interest' | |
and account !~ 'Insurance' | |
and account !~ 'Travel' | |
and not virtual | |
group by | |
xtn_month | |
) x | |
order by | |
xtn_month | |
) x | |
) x | |
) x; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment