2

The goal is to graph the total volume of created orders over time in a monthly digest

WITH monthly_sums AS (
  SELECT
    date_trunc('month', created_at) AS month,
    sum(count(created_at)) OVER (ORDER BY date_trunc('month', created_at)) AS sum
  FROM orders
  GROUP BY date_trunc('month', created_at)
)
SELECT
  to_char(date_range.month, 'Month') AS month,
  COALESCE(monthly_sums.sum, 0) AS total
FROM generate_series('2014-10-01'::date, CURRENT_DATE, '1 month') date_range(month)
LEFT OUTER JOIN monthly_sums
ON monthly_sums.month = date_range.month;

Which returns:

   month   | total
-----------+-------
 October   |     0
 November  |     0
 December  |     0
 January   |     1
 February  |     0     <-- should be 1
 March     |     3
(6 rows)

selecting from monthly_sums returns:

        month        | sum
---------------------+-----
 2015-01-01 00:00:00 |   1
                     |         <-- no records created in February
 2015-03-01 00:00:00 |   3
                     |   3
(3 rows)

The problem is there were no orders in February so the total is coalesced into 0. How can I alter or rethink this query in order to get the desired result?

2
  • 1
    You need to do the running sum in the outer query, not inside the CTE
    – user330315
    Mar 5, 2015 at 21:05
  • how could that be done? Mar 5, 2015 at 21:12

2 Answers 2

1

I am unfamiliar with the postgresql syntax for this construct, but the general pattern across all SQL engines for implementing this type of operation efficiently is always the following:

  1. Aggregate by month;
  2. Left join from the full set of desired periods to the aggregates in (1), coalescing absent sums to zero;
  3. Perform the running summation by period.

Use either CTE's or subqueries to build 1, 2, and 3 successively.

0
0

following Pieter's answer, this altered query gives the correct result

WITH monthly_counts AS (
  SELECT
    date_trunc('month', created_at) AS month,
    count(created_at) AS count
  FROM orders
  GROUP BY date_trunc('month', created_at)
)
SELECT
  to_char(sq.month, 'Month') AS month,
  sum(sq.count) OVER (ORDER BY sq.month)
FROM
  (SELECT
    date_range.month,
    COALESCE(monthly_counts.count, 0) AS count
  FROM generate_series('2014-10-01'::date, CURRENT_DATE, '1 month') date_range(month)
  LEFT OUTER JOIN monthly_counts
  ON monthly_counts.month = date_range.month) AS sq;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.