I have a query in Oracle that creates a pivot table and I'm trying to convert it over to postgres.
In Oracle I had the following:
CREATE OR REPLACE VIEW PROGRAM_EXPENDITURES AS (
SELECT ROWNUM AS ID, a.*
FROM (
SELECT * FROM (
SELECT 8400000 AS PROGRAM_TOTAL, PROGRAM_INCOME, INCENTIVE_AMT_NUM, APP_STATUS FROM HB357
)
PIVOT (
SUM(INCENTIVE_AMT_NUM) as incentive, sum(program_income) as income for app_status in ('approved' approved, 'pending' pending, 'void' void)
)
)a)
Which gives an output of:
ID | PROGRAM_TOTAL | APPROVED_INCENTIVE | PENDING_INCENTIVE | VOID_INCENTIVE | APPROVED_INCOME | PENDING_INCOME | VOID_INCOME
------------------------------------------------------------------------------------------------------------------------------
1 84000000 3386600 2108.75 1500 2000000 5000000 100
I read this post about using CASE STATEMENTS
in PG and have done the following:
SELECT
8400000 AS PROGRAM_TOTAL,
CASE WHEN hb357.app_status = 'Approved' THEN SUM(hb357.incentive_amt_num) END as approved_incentive,
CASE WHEN hb357.app_status = 'Pending' THEN SUM(hb357.incentive_amt_num) END as pending_incentive,
CASE WHEN hb357.app_status = 'Void' THEN SUM(hb357.incentive_amt_num) END as void_incentive,
CASE WHEN hb357.app_status = 'Approved' THEN SUM(hb357.program_income) END as approved_income,
CASE WHEN hb357.app_status = 'Pending' THEN SUM(hb357.program_income) END as pending_income,
CASE WHEN hb357.app_status = 'Void' THEN SUM(hb357.program_income) END as void_income
FROM WOODBURN.HB357
GROUP BY hb357.app_status
But this splits the results by app status into separate rows because of the GROUP BY
statement.
But I need the all on the same row. So that results look like this: