WITH
preagg AS (
SELECT
    director_descr
    ,quota_rep_descr
    ,part
    ,bill_cust
    ,ship_cust
    ,order_month
    ,iterdef
    ,sum(fb_val_loc * r_rate) FILTER (WHERE iter = 'copy') sales
    ,sum(fb_cst_loc * c_rate) FILTER (WHERE iter = 'copy') scogs
    ,sum(fb_val_loc * r_rate) FILTER (WHERE iter <> 'copy') sales_adj
    ,sum(fb_cst_loc * c_rate) FILTER (WHERE iter <> 'copy') scogs_adj
FROM
    rlarp.osm_fcpool
WHERE
    order_season = 2020
GROUP BY
    director_descr
    ,quota_rep_descr
    ,part
    ,bill_cust
    ,ship_cust
    ,order_month
    ,iterdef
)
SELECT
    director_descr
    ,quota_rep_descr
    ,to_char(sum(sales),'999,999,999') sales
    ,to_char(sum(sales - scogs),'999,999,999')  margin
    ,to_char(sum(sales_adj),'999,999,999')  sales_adj
    ,to_char(sum(sales_adj - scogs_adj),'999,999,999')  margin_adj
    ,count(iterdef) "# of changes"
FROM
    preagg
GROUP BY 
    GROUPING SETS (
        (director_descr,quota_rep_descr),
        (director_descr),
        ()
    )
ORDER BY
    director_descr
    ,quota_rep_descr
