forecast_api/route_sql/build/open_timing.sql

96 lines
2.3 KiB
MySQL
Raw Normal View History

BEGIN;
2019-03-24 23:25:23 -04:00
WITH
mseq AS (
SELECT * FROM
(
VALUES
('Jun',1,6,-1)
,('Jul',2,7,-1)
,('Aug',3,8,-1)
,('Sep',4,9,-1)
,('Oct',5,10,-1)
,('Nov',6,11,-1)
,('Dec',7,12,-1)
,('Jan',8,1,0)
,('Feb',9,2,0)
,('Mar',10,3,0)
,('Apr',11,4,0)
,('May',12,5,0)
) x(m,s,cal,yr)
)
,alldates AS (
SELECT
shipgrp
,to_char(orderdate,'Mon') orderm
,extract(month FROM age(requestdate,orderdate)) rmo
,(sum((shipdate - requestdate)* (fb_val_loc * r_rate))/sum(fb_val_loc * r_rate))::int wav_lag
--,sum(fb_val_loc * r_rate) value_usd
FROM
rlarp.osm
WHERE
adj_orderdate >= '2017-06-01'
AND calc_status||flag <> 'CLOSEDREMAINDER' --exclude short ships when building order adjustments
AND adj_orderdate <= adj_shipdate
AND fspr IS NOT NULL
GROUP BY
shipgrp
,to_char(orderdate,'Mon')
,extract(month FROM age(requestdate,orderdate))
HAVING
sum(fb_val_loc * r_rate) <> 0
)
,lag AS (
SELECT
shipgrp
,orderm
,rmo
,wav_lag
FROM
alldates
ORDER BY
shipgrp
,orderm
,rmo
)
,opord AS (
SELECT
shipgrp
,orderdate
,requestdate
,shipdate
,to_char(orderdate,'Mon') orderm
,extract(month FROM age(requestdate,orderdate)) rmo
,sum(fb_val_loc * r_rate) value_usd
FROM
rlarp.osm
WHERE
calc_status NOT IN ('CANCELED','CLOSED')
GROUP BY
shipgrp
,orderdate
,requestdate
,shipdate
,to_char(orderdate,'Mon')
,extract(month FROM age(requestdate,orderdate))
ORDER BY
value_usd DESC
)
,upd AS (
UPDATE rlarp.osmfs o SET
adj_shipdate = greatest(shipdate + lag.wav_lag + 5 ,shipdate)
2019-03-24 23:25:23 -04:00
FROM
lag
WHERE
lag.shipgrp = o.shipgrp
AND lag.orderm = to_char(o.orderdate,'Mon')
AND lag.rmo = extract(month FROM age(o.requestdate,o.orderdate))
AND o.calc_status in ('BACKORDER','OPEN')
RETURNING *
2019-03-24 23:25:23 -04:00
)
SELECT
sum(fb_val_loc *r_rate) filter (where adj_shipdate < '2019-04-01')
,sum(fb_val_loc *r_rate) filter (where adj_shipdate >= '2019-04-01')
from upd;
COMMIT;