forecast_api/route_sql/adj_totals.sql

55 lines
1.4 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
,tag
2020-02-19 17:15:43 -05:00
,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
2021-04-05 15:22:20 -04:00
order_season = 2022
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
,tag
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) FILTER (WHERE tag <> 'Initial Build'),'999,999,999') sales_adj
,to_char(sum(sales_adj - scogs_adj) FILTER (WHERE tag <> 'Initial Build'),'999,999,999') margin_adj
,count(DISTINCT logid) FILTER (WHERE tag <> 'Initial Build') "# of changes"
,COUNT(logid) FILTER (WHERE tag <> 'Initial Build') "# of rows added"
,(max(stamp) FILTER (WHERE tag <> 'Initial Build'))::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
2021-04-05 15:22:20 -04:00
,quota_rep_descr