forecast_api/offline/set_quota_rep.sql
2020-02-20 14:32:43 -05:00

112 lines
3.5 KiB
SQL

With
REPC AS (
SELECT
LTRIM(RTRIM(C.A9)) RCODE
,LTRIM(RTRIM(C.A9)) || ' - ' || C.A30 REPP
,COALESCE(Q.DIR,'Other') DIRECTOR
FROM
LGDAT.CODE C
LEFT OUTER JOIN RLARP.QRH Q ON
Q.QR = LTRIM(RTRIM(C.A9))
WHERE
C.A2 = 'MM'
)
,r AS (
SELECT
b.quota_rep base_rep
--quota rep--------------------------------------------
,RTRIM(
COALESCE(
--retail items go to currep, or if null go to 90005
CASE WHEN COALESCE(b.glec) IN ('1RE','1CU') THEN
CASE WHEN bc.bvctry = 'CAN' THEN
--Rachel Bowman
'50300'
ELSE
--retail chain got to Mark Wilkinson
CASE COALESCE(cg.cgrp,bc.bvname)
WHEN 'THE HOME DEPOT' THEN '90005'
WHEN 'DO IT BEST' THEN '90005'
WHEN 'ACE HARDWARE' THEN '90005'
WHEN 'ALDI' THEN '90005'
WHEN 'AMAZON.COM' THEN '90005'
WHEN 'GARDEN RIDGE CORP' THEN '90005'
--all other retail goes to Doran Marable
ELSE '50200'
END
END
ELSE
CASE WHEN COALESCE(b.ming) = 'B52' THEN
'PW'
--gdir, ndir go to bill-to rep
ELSE
CASE WHEN bc.bvclas IN ('GDIR','NDIR') THEN
bc.bvsalm
ELSE
sc.bvsalm
END
END
END
,''
)
) revised_rep
,sum(fb_val_loc * r_rate) sales
FROM
rlarp.osm_fcpool b
LEFT OUTER JOIN LGDAT.CUST BC ON
BC.BVCUST = b.BILL_CUST
LEFT OUTER JOIN LGDAT.CUST SC ON
SC.BVCUST = b.SHIP_CUST
LEFT OUTER JOIN RLARP.FFCUST CG ON
CG.CUSTN = BC.BVCUST
LEFT OUTER JOIN RLARP.FFCUST SG ON
SG.CUSTN = SC.BVCUST
GROUP BY
b.quota_rep
--quota rep--------------------------------------------
,RTRIM(
COALESCE(
--retail items go to currep, or if null go to 90005
CASE WHEN COALESCE(b.glec) IN ('1RE','1CU') THEN
CASE WHEN bc.bvctry = 'CAN' THEN
--Rachel Bowman
'50300'
ELSE
--retail chain got to Mark Wilkinson
CASE COALESCE(cg.cgrp,bc.bvname)
WHEN 'THE HOME DEPOT' THEN '90005'
WHEN 'DO IT BEST' THEN '90005'
WHEN 'ACE HARDWARE' THEN '90005'
WHEN 'ALDI' THEN '90005'
WHEN 'AMAZON.COM' THEN '90005'
WHEN 'GARDEN RIDGE CORP' THEN '90005'
--all other retail goes to Doran Marable
ELSE '50200'
END
END
ELSE
CASE WHEN COALESCE(b.ming) = 'B52' THEN
'PW'
--gdir, ndir go to bill-to rep
ELSE
CASE WHEN bc.bvclas IN ('GDIR','NDIR') THEN
bc.bvsalm
ELSE
sc.bvsalm
END
END
END
,''
)
)
)
SELECT
b.repp
,v.repp
,r.sales
FROM
r
LEFT OUTER JOIN REPC b on
b.rcode = r.base_rep
LEFT OUTER JOIN REPC v on
v.rcode = r.revised_rep