Search code examples
postgresqlpivotcrosstabcoalesce

Pivoting user revenues by month in PostgreSQL


I have the following syntax below when writing my query in PostgreSQL. This query works just fine. My only issue is the null values that appear below.

I want to use Coalesce() in this query but I'm stuck. Is there a way in adjusting this query so that I can add Coalesce to this query?

-- Import tablefunc
CREATE EXTENSION IF NOT EXISTS tablefunc;

SELECT * FROM CROSSTAB($$
  SELECT
    user_id,
    DATE_TRUNC('month', order_date) :: DATE AS delivr_month,
    SUM(meal_price * order_quantity) :: FLOAT AS revenue
  FROM meals
  JOIN orders ON meals.meal_id = orders.meal_id
 WHERE user_id IN (0, 1, 2, 3, 4)
   AND order_date < '2018-09-01'
 GROUP BY user_id, delivr_month
 ORDER BY user_id, delivr_month;
$$)
-- Select user ID and the months from June to August 2018
AS ct (user_id INT,
       "2018-06-01" FLOAT,
       "2018-07-01" FLOAT,
       "2018-08-01" FLOAT)     
ORDER BY user_id ASC;

Output:

enter image description here


Solution

  • SELECT 
           user_id,
           coalesce("2018-06-01", 0.0) "2018-06-01",
           coalesce("2018-07-01", 0.0) "2018-07-01",
           coalesce("2018-08-01", 0.0) "2018-08-01"
     FROM CROSSTAB($$
      SELECT
        user_id,
        DATE_TRUNC('month', order_date) :: DATE AS delivr_month,
        SUM(meal_price * order_quantity) :: FLOAT AS revenue
      FROM meals
      JOIN orders ON meals.meal_id = orders.meal_id
     WHERE user_id IN (0, 1, 2, 3, 4)
       AND order_date < '2018-09-01'
     GROUP BY user_id, delivr_month
     ORDER BY user_id, delivr_month;
    $$)
    -- Select user ID and the months from June to August 2018
    AS ct (user_id INT,
           "2018-06-01" FLOAT,
           "2018-07-01" FLOAT,
           "2018-08-01" FLOAT)     
    ORDER BY user_id ASC;