Skip to content

Instantly share code, notes, and snippets.

@peterkeen
Created March 4, 2012 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterkeen/1969827 to your computer and use it in GitHub Desktop.
Save peterkeen/1969827 to your computer and use it in GitHub Desktop.
Complicated ledger query
-- 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