I was once tasked with writing a pretty complicated query to quantify Watsi’s weekly growth. We wanted to take into account monthly donations though. How does one do that when monthly donations are all charged on the first of the month? How do we include tips to our overhead fund?
I recognize there are all sorts of ways to do this. Hell, I could have
written this in
Ruby, and I almost did, but we used Heroku’s
Dataclips which allowed us to get near-realtime results.
Let’s take a slightly simpler example: A small business sells widgets. Widgets are sold for all different prices, and you can even set up a recurring order that is charged on the first of the month.
Imagine we have a very simple table
purchases that looks something
|created_at||timestamp without time zone|
|refunded_at||timestamp without time zone|
Some sample data:
|3||1300||2014-08-24 23:30:00||2014-08-24 23:31:00||false|
So, given this info, we calculate our weekly amount as:
(daily totals + avg daily totals from recurring) / # of weeks in month
Note: I’m going to ignore time zones for brevity, but assume I’m setting
In any other database I would have had to either use
temp tables or
but PostgreSQL has what are called Common Table Expressions
WITH queries allow us to turn
sub-selects into named tables without the need
to generate actual
can be turned into this:
This trivial example doesn’t do the greatest job in showing the power of CTE’s, but the final query below will.
OK, so let’s see some SQL:
which will yield results like so:
Now let’s add the month to this result set, which wasn’t possible before
because of the
group by clause.
Now we need to calculate each month’s recurring revenue:
But now we have to average in the recurring into each day. How can we handle the different number of days in a month? With another query:
August has 31 days, September has 30. This approach handles leap years in February too.
We now need to find the actual average per day based on the month:
So now we have:
Now it’s time to start mashing these tables together:
OK, we’re close! We have
daily totals and
avg daily totals from recurring.
Last calculation we need to do is add up the amounts and
group by the week.
This is the reduction I alluded to above:
Finally, we get our actual weekly totals:
Notice that the start of the week shifted. Take heed!
The final query
In all its glory, or something:
I hope you enjoyed this venture into using CTE’s to build up a simple result from a decently complex, for SQL, report. I’ve grown quite fond of CTE’s and luckily I used PostgreSQL exclusively for my last several projects. The expressive power to compose SQL queries like this is one of the many things I love about PostgreSQL.
Discussion over on hn.
ps: My friend Jacob asked how well this performs. From what I can tell it performs really well, but I haven’t had the chance to benchmark it yet. I’m hoping to write up how it performs 1) with more data and 2) against an implementation in Ruby.
 I say “near-realtime” because Heroku caches the results for some period.- Jesse