-- Using PostgreSQL crosstab() Function SELECT * FROM crosstab( $$ SELECT e.last_name || ' ' || e.first_name salesman, date_part('Mon',order_date) AS order_month, SUM(ROUND((quantity * unit_price)::numeric, 2)) AS order_total FROM employees e JOIN orders o ON e.employee_id = o.employee_id JOIN order_details od ON o.order_id = od.order_id WHERE date_part('year', order_date) = 1997 AND date_part('month', order_date) BETWEEN 1 AND 4 GROUP BY 1, 2 UNION ALL SELECT 'month_total', date_part('month', order_date) AS order_month, ROUND(SUM(quantity * unit_price)::numeric, 2) AS order_total FROM orders o JOIN order_details od ON o.order_id = od.order_id WHERE date_part('year', order_date) = 1997 AND date_part('month', order_date) BETWEEN 1 AND 4 GROUP BY 1,2 $$, $$ SELECT DISTINCT date_part('month', order_date) AS order_month FROM orders WHERE date_part('year', order_date) = 1997 AND date_part('month', order_date) BETWEEN 1 AND 4 ORDER BY 1 $$ ) AS ct (salesman text, Jan numeric, Feb numeric, Mar numeric, Apr numeric);