forecast_api/build/rep_totals.sql

52 lines
1.2 KiB
MySQL
Raw Normal View History

2019-04-03 09:56:01 -04:00
WITH
preagg AS (
SELECT
2020-02-19 17:15:43 -05:00
coalesce(director,'None') director
,coalesce(quota_rep_descr,'None') quota_rep_descr
2019-04-03 09:56:01 -04:00
,part
2020-02-19 17:15:43 -05:00
,bill_cust_descr
,ship_cust_descr
2019-04-03 09:56:01 -04:00
,order_month
2020-02-19 17:15:43 -05:00
,doc->>'stamp' stamp
,logid
,sum(value_usd) FILTER (WHERE iter = 'copy') sales
,sum(cost_usd) FILTER (WHERE iter = 'copy') scogs
,sum(value_usd) FILTER (WHERE iter <> 'copy') sales_adj
,sum(cost_usd) FILTER (WHERE iter <> 'copy') scogs_adj
2019-04-03 09:56:01 -04:00
FROM
2020-02-19 17:15:43 -05:00
rlarp.osm_pool
LEFT OUTER JOIN rlarp.osm_log ON
id = logid
2019-04-03 09:56:01 -04:00
WHERE
2020-02-19 17:15:43 -05:00
order_season = 2021
2019-04-03 09:56:01 -04:00
GROUP BY
2020-02-19 17:15:43 -05:00
director
2019-04-03 09:56:01 -04:00
,quota_rep_descr
,part
2020-02-19 17:15:43 -05:00
,bill_cust_descr
,ship_cust_descr
2019-04-03 09:56:01 -04:00
,order_month
2020-02-19 17:15:43 -05:00
,doc->>'stamp'
,logid
2019-04-03 09:56:01 -04:00
)
SELECT
2020-02-19 17:15:43 -05:00
director
2019-04-03 09:56:01 -04:00
,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
2020-02-19 17:15:43 -05:00
,count(DISTINCT logid) "# of changes"
,COUNT(logid) "# of rows added"
,(max(stamp))::timestamptz "last edit"
2019-04-03 09:56:01 -04:00
FROM
preagg
GROUP BY
GROUPING SETS (
2020-02-19 17:15:43 -05:00
(director,quota_rep_descr),
(director),
2019-04-03 09:56:01 -04:00
()
)
ORDER BY
2020-02-19 17:15:43 -05:00
director
,quota_rep_descr