WITH
SEG AS (
    SELECT
        GLEC
        ,SEGM
    FROM
        (
            VALUES
            ('1CU','Sustainable'),
            ('1SU','Sustainable'),
            ('1GR','Greenhouse'),
            ('1NU','Nursery'),
            ('1RE','Retail'),
            ('2WI','Greenhouse'),
            ('3BM','Other'),
            ('3CO','Other'),
            ('3PE','Other'),
            ('3PP','Other'),
            ('4CO','Other'),
            ('4RA','Other'),
            ('9MI','Other'),
            ('9SA','Other'),
            ('9TO','Other')
        ) X(GLEC, SEGM)
)
SELECT 
    o.*
    ,o.lbs * o.fb_qty ext_lbs
    ,COALESCE(s.segm,o.glec) segm
    ,og.sortmo omon
    ,sg.sortmo smon
    ,COALESCE(f.flag,CASE WHEN o.shipgrp = 'TARGET STORES' THEN 'RETAIL' ELSE 'YoY' END) price_flag
    ,coalesce(i.futstdus,o.fb_cst_loc_cur * c_rate) cash_cost
    ,CASE WHEN o.shipgrp = 'TARGET STORES' THEN 'Giorgio' ELSE r.director END director
FROM 
    rlarp.osmfs o
    LEFT OUTER JOIN seg s ON 
        s.glec = o.glec
    LEFT OUTER JOIN rlarp.gld og ON 
        o.odate <@ og.drange
    LEFT OUTER JOIN rlarp.gld sg ON 
        o.sdate <@ sg.drange
    LEFT OUTER JOIN rlarp.cust_flag f ON 
        f.shipgrp = o.shipgrp 
        AND f.dsm = o.dsm
    LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
        i.item = o.part
    LEFT OUTER JOIN rlarp.repc r ON 
        r.rcode = substring(o.dsm,1,5)
