WITH
newc AS (
    SELECT * FROM (VALUES
    ('4 ACES','10041 - TAMARA RISKEN'),
    ('A&W ANNUALS','10039 - DUSTIN KUYKENDOLL'),
    ('A GARDEN CENTER','30053 - SKYE SAWYER'),
    ('ALASKA GDN & PET SUPPLY RET','30053 - SKYE SAWYER'),
    ('ALASKA MILL AND FEED','30053 - SKYE SAWYER'),
    ('ALPHA NURSERY','30053 - SKYE SAWYER'),
    ('ANDYS GARDENS','10048 - PHILIP BIEDENBACH'),
    ('ARNOLDS GREENHOUSE INC','10041 - TAMARA RISKEN'),
    ('ASHCOMBE FARM & GREENHOUSE','10048 - PHILIP BIEDENBACH'),
    ('AVA NURSERY','10046 - DUSTIN KUYKENDOLL 2'),
    ('BAYSIDE GARDEN CENTER','13027 - STEVE RUSTEBERG'),
    ('BAYVIEW GREENHOUSES','40039 - DAVE BODO'),
    ('BEAUTIFUL LAND PRODUCTS','13027 - STEVE RUSTEBERG'),
    ('BEAVER BARK LTD','30053 - SKYE SAWYER'),
    ('BEDROCK NURSERY','10041 - TAMARA RISKEN'),
    ('BELLE INVESTMENTS','10039 - DUSTIN KUYKENDOLL'),
    ('BLUE HERON FARM','30053 - SKYE SAWYER'),
    ('BOBBY MURRAY FARMS','10041 - TAMARA RISKEN'),
    ('BOEKESTYN GREENHOUSES LTD','40039 - DAVE BODO'),
    ('BREEZY HILL NURSERY','13027 - STEVE RUSTEBERG'),
    ('BRENTANOS TREE FARM','30053 - SKYE SAWYER'),
    ('BRIGGS NURSERY','30053 - SKYE SAWYER'),
    ('CAAN FLORAL CO INC','13027 - STEVE RUSTEBERG'),
    ('CAPOGNA FLOWERS','40039 - DAVE BODO'),
    ('CARPINITO BROTHERS INC','30053 - SKYE SAWYER'),
    ('CHRIS DOYLE PLANT BROKERAGE','10041 - TAMARA RISKEN'),
    ('CINDYS GREENHOUSE','13027 - STEVE RUSTEBERG'),
    ('D''ADDIO FAMILY NURSERY','10048 - PHILIP BIEDENBACH'),
    ('DAHLINGHAUS VENTURES LLC','10048 - PHILIP BIEDENBACH'),
    ('DAYNABROOK GREENHOUSES','10048 - PHILIP BIEDENBACH'),
    ('DESERT FOREST NURSERY','30035 - RODNEY RIOS'),
    ('DESERT HORIZON NURSERY','30035 - RODNEY RIOS'),
    ('DETWEILER''S FLOWERS','10048 - PHILIP BIEDENBACH'),
    ('DGI','10035 - MATTHEW STAAL'),
    ('DOAN''S NURSERY INC.','10041 - TAMARA RISKEN'),
    ('DRY LAND NATIVE GRASSES','10041 - TAMARA RISKEN'),
    ('EDGEWOOD GREENHOUSE','13027 - STEVE RUSTEBERG'),
    ('FERGUSON LANDSCAPE','13027 - STEVE RUSTEBERG'),
    ('FISHER FARMS','30053 - SKYE SAWYER'),
    ('GEORGE''S PLANT FARM','10040 - RYAN CHITWOOD'),
    ('GIESEL''S GREENHOUSE','10041 - TAMARA RISKEN'),
    ('GILSON FAMILY ENTERPRISE','10042 - JEREMY RHAULT'),
    ('GOLD COAST FARMS LLC','30035 - RODNEY RIOS'),
    ('GOLD HILL NURSERY','30053 - SKYE SAWYER'),
    ('GROWERS NURSERY SUPPLY INC','30053 - SKYE SAWYER'),
    ('HEIRLOOM ROSES','30053 - SKYE SAWYER'),
    ('HENRY WHALEN AND SONS GHSE','10043 - CHERISSE GILSTROP'),
    ('HIGHLAND FARMS','12028 - JACOB WILKINSON'),
    ('HILLEN NURSERY LTD','40039 - DAVE BODO'),
    ('HONEYMOON ACRES','13027 - STEVE RUSTEBERG'),
    ('HOSTYN HILL GREENHOUSE','10041 - TAMARA RISKEN'),
    ('HSU''S','13027 - STEVE RUSTEBERG'),
    ('HUIZENGA BRO GREENHOUSE INC','10035 - MATTHEW STAAL'),
    ('I & G FARM INC','10043 - CHERISSE GILSTROP'),
    ('IMPERIAL''S GARDEN INC','30053 - SKYE SAWYER'),
    ('J FRANK GAUDET TREE NURSERY','40040 - TINA PETTIGREW'),
    ('JACOBSONS GREENHOUSE','30053 - SKYE SAWYER'),
    ('JAMPLAST INC','13027 - STEVE RUSTEBERG'),
    ('JEFF PARSLEY PLANT FARM','10041 - TAMARA RISKEN'),
    ('JEFFEREYS GREENHOUSES','40039 - DAVE BODO'),
    ('KATOS NURSERY','40042 - TOM MORRIS'),
    ('KATYDID GREENHOUSE','10040 - RYAN CHITWOOD'),
    ('LANCASTER FARM','10040 - RYAN CHITWOOD'),
    ('LENO PLANT FARM','10041 - TAMARA RISKEN'),
    ('LIMA GREENHOUSES','30053 - SKYE SAWYER'),
    ('LINNAEA NURSERIES LTD','40042 - TOM MORRIS'),
    ('MAGNOLIA GARDENS','10041 - TAMARA RISKEN'),
    ('MARCUMS NURSERY','10041 - TAMARA RISKEN'),
    ('MARTIN''S NURSERY INC','10047 - RYAN CHITWOOD 2'),
    ('MAYS GREENHOUSE','10048 - PHILIP BIEDENBACH'),
    ('MCCALLISTERS LNDSCP SUPPLY','10041 - TAMARA RISKEN'),
    ('MCCALLS NURSERIES INC','30054 - JASON MOTTIN'),
    ('MEADOWLARK ORNAMENTALS LLC','12028 - JACOB WILKINSON'),
    ('MEDARY ACRES GHSE','13027 - STEVE RUSTEBERG'),
    ('MEDFORD NURSERY INC','10043 - CHERISSE GILSTROP'),
    ('MESQUITE VALLEY GROWERS','30035 - RODNEY RIOS'),
    ('MILLERS BLUE MOUNTAIN GHSE','10043 - CHERISSE GILSTROP'),
    ('MR GREENJEANS FARM MARKET','10043 - CHERISSE GILSTROP'),
    ('MULTIFAB, INC','30053 - SKYE SAWYER'),
    ('NATURALLY BEAUTIFUL PLANT PROD','10043 - CHERISSE GILSTROP'),
    ('NORTHWEST PLANT COMPANY','30053 - SKYE SAWYER'),
    ('OSO GROWERS INC.','10041 - TAMARA RISKEN'),
    ('PARSLEYS PLANT FARM','10041 - TAMARA RISKEN'),
    ('PAYNES NURSERIES & GREENHOUSE','12028 - JACOB WILKINSON'),
    ('PHELPS NURSERY','10048 - PHILIP BIEDENBACH'),
    ('PINE VIEW FARM','10048 - PHILIP BIEDENBACH'),
    ('QUALITREE PROPAGATORS','40042 - TOM MORRIS'),
    ('RAZBUTON INC','10039 - DUSTIN KUYKENDOLL'),
    ('REARDON NURSERY','30053 - SKYE SAWYER'),
    ('SCHROCK SALES','10048 - PHILIP BIEDENBACH'),
    ('SHANER AVENUE NURSERY','10035 - MATTHEW STAAL'),
    ('SHERMAN PLASTICS','13027 - STEVE RUSTEBERG'),
    ('SLC STORE','12028 - JACOB WILKINSON'),
    ('SMITH NURSERY','10041 - TAMARA RISKEN'),
    ('STARLING NURSERY','10046 - DUSTIN KUYKENDOLL 2'),
    ('STEUBER GREENHOUSE','13027 - STEVE RUSTEBERG'),
    ('STEWARTS GREENHOUSE','10046 - DUSTIN KUYKENDOLL 2'),
    ('STOKLEY NURSERY','10047 - RYAN CHITWOOD 2'),
    ('SUAREZ PLANT FARM','10041 - TAMARA RISKEN'),
    ('SUN NURSERIES','10043 - CHERISSE GILSTROP'),
    ('SUNLAND NURSERY','12028 - JACOB WILKINSON'),
    ('SUNRISE GREENHOUSES','40039 - DAVE BODO'),
    ('TEJANA NURSERY','10041 - TAMARA RISKEN'),
    ('THOMAS BECNEL','10041 - TAMARA RISKEN'),
    ('THOMAS BECNEL CITRUS','10041 - TAMARA RISKEN'),
    ('TOM DE SANTO GREENHOUSES','30053 - SKYE SAWYER'),
    ('TONYS GARDEN CENTER','30053 - SKYE SAWYER'),
    ('TREESEARCH FARMS INC','10041 - TAMARA RISKEN'),
    ('UNITED CENTRAL ORCHIDS','13027 - STEVE RUSTEBERG'),
    ('VAN BELLE NURSERY','40042 - TOM MORRIS'),
    ('VAN KLAVEREN''S NURSERY LLC','30053 - SKYE SAWYER'),
    ('VARGAS NURSERY','10041 - TAMARA RISKEN'),
    ('WALNUT GROVE NURSERY','40042 - TOM MORRIS'),
    ('WATERTOWN FLORAL','13027 - STEVE RUSTEBERG'),
    ('WAYFAIR LLC','90015 - ANN MARIE FOX'),
    ('WEAKLAND GREENHOUSES','12028 - JACOB WILKINSON'),
    ('WOODS GREENHOUSE','10043 - CHERISSE GILSTROP'),
    ('YC NURSERIES INC','10041 - TAMARA RISKEN'),
    ('A&R SPADA FARMS LLC','30053 - SKYE SAWYER'),
    ('CI FARMS LLC','30054 - JASON MOTTIN'),
    ('GOLDEN EAGLE TREES','40042 - TOM MORRIS'),
    ('TSC NURSERY SALES LTD','40042 - TOM MORRIS')
    ) x(Renamed,ReRep)
)
,profile AS (
    SELECT * FROM rlarp.osm WHERE shipgrp IN (select distinct renamed FROM newc ) AND oseas >= 2018
)
-- SELECT * FROM profile
,checkc AS (
SELECT shipgrp, min(oseas) oseas FROM profile GROUP BY shipgrp
)
-- select * from checkc
-- SELECT cust, sum(fb_qty) FROM newc LEFT OUTER JOIN profile ON shipgrp = cust GROUP by cust
----grouped prices-------------
,npgrp AS (
	SELECT
		o.bill_dba 
		,o.ship_dba
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
		,o.part
		,o.odate
		,o.qtyord
		,i.nwht * CASE WHEN i.nwun = 'KG' THEN 2.2 ELSE 1 END lbs
		,i.mpck pltq
		,ROUND(o.sales_usd / o.qty,5) price
		,(o.pricing->>'guidance_price')::NUMERIC guidance
	    ,(o.pricing->>'floor'  )::numeric(15,5) floor        
	    ,(o.pricing->>'ceiling')::numeric(15,5) ceiling   
	    ,(o.pricing->>'uselimits')::boolean uselimits
	FROM
	 	rlarp.osm_stack o
	 	LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
	 		i.item = o.part
        INNER JOIN checkc c ON 
            c.shipgrp = o.customer
            AND c.oseas = o.oseas
	WHERE 
		VERSION = 'Actual' 
		AND o.oseas >= 2018
		AND calc_status <> 'CANCELED' 
		AND o.fs_line = '41010'
		AND o.part <> ''
		AND substring(o.glec,1,1) <= '2'
		AND o.qty <> 0
        AND o.sseas IS NOT NULL
        AND ROUND(o.sales_usd / o.qty,5) 
        -- AND customer in (select distinct renamed FROM newc )
	GROUP BY 
		o.bill_dba 
		,o.ship_dba
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
		,o.part
		,o.odate
		,o.qtyord
		,o.pounds
		,o.pallets
		,ROUND(o.sales_usd / o.qty,5)
		,i.nwht * CASE WHEN i.nwun = 'KG' THEN 2.2 ELSE 1 END
		,i.mpck
		,(o.pricing->>'guidance_price')::NUMERIC
	    ,(o.pricing->>'floor'  )::numeric(15,5)        
	    ,(o.pricing->>'ceiling')::numeric(15,5)
	    ,(o.pricing->>'uselimits')::boolean
)
----sequenced for most recent price------------
,nseq AS (
	SELECT 
		 bill_dba 
		,ship_dba
		,part
		,odate
		,qtyord
		,lbs
		,pltq
		,price
		,guidance
	    ,floor        
	    ,ceiling   
	    ,uselimits
	    ,row_number() OVER (PARTITION BY bill_dba, ship_dba, part ORDER BY odate desc) rn
	    ,round(avg(price) over (PARTITION BY bill_dba, ship_dba, part),5) avgprice
	FROM 
		npgrp
)
-- SELECT * FROM seq WHERE rn = 1
,ngrp AS (
    SELECT 
        o.account
        ,o.shipgrp
        ,o.chan
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
        ,o.part
        ,o.glec
        ,o.oseas
        -- ,o.odate
        ,og.sortmo omon
        ,o.sseas
        -- ,o.sdate
        ,sg.sortmo smon
        -- ,o.calc_status
        ,ROUND(sum(fb_qty * lbs),5) lbs
        ,ROUND(sum(fb_qty),2) qty 
        ,ROUND(sum(fb_val_loc * r_rate),2) sales_usd
        ,ROUND(sum(fb_cst_loc_cur * c_rate),2) cost_curstd_usd
    FROM 
        profile o
        LEFT OUTER JOIN rlarp.gld og ON 
            o.odate BETWEEN og.sdat and og.edat
        LEFT OUTER JOIN rlarp.gld sg ON
            o.sdate BETWEEN sg.sdat and sg.edat
        LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
            i.item = o.part
    WHERE
        true
        -- iter IN ('actuals','actuals_plug','copy')
        AND fs_line = '41010' 
        AND substring(o.glec,1,1) <= '2'
        AND o.calc_status <> 'CANCELED'
        AND o.sseas IS NOT NULL
    GROUP BY 
        o.account
        ,o.shipgrp
        ,o.chan
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
        ,o.part
        ,o.glec
        ,o.oseas
        -- ,o.odate 
        ,og.sortmo
        ,o.sseas
        -- ,o.sdate
        ,sg.sortmo
        -- ,o.calc_status
)
-- SELECT * FROM grp
,nguid AS (
    SELECT
         grp.account
        ,grp.shipgrp
        ,grp.chan
        ,r.repp dsm
        ,r.director
        ,grp.shipgrp||'.'||r.repp lu
        -- ,grp.partgroup
        -- ,grp.pricegroup
        ,grp.part
        -- ,grp.glec
        ,2026  oseas
        ,grp.omon 
        -- ,grp.odate 
        ,(2026- grp.oseas) + grp.sseas sseas
        ,grp.smon
        -- ,grp.sdate
        ,grp.lbs
        ,grp.qty 
        ,grp.sales_usd
        ,CASE WHEN round(grp.sales_usd/grp.qty,5) = 0 THEN null ELSE round(grp.sales_usd/grp.qty,5) END hist_price
        ,grp.cost_curstd_usd
        ,sum(grp.lbs) OVER (PARTITION BY shipgrp,  dsm) shiplbs
        ,CASE WHEN seq.floor = 0 THEN null else seq.floor END floor
        ,CASE WHEN seq.ceiling = 0 THEN null else seq.ceiling END ceiling
        ,seq.uselimits
        ,seq.price 
        ,seq.avgprice
        ,seq.pltq
        ,ROUND(CASE WHEN seq.uselimits THEN 
            CASE 
                WHEN glec = '1NU' THEN
                    --if more than 8/24 pallets, use floor
                    CASE WHEN grp.qty >= 24*seq.pltq THEN seq.floor
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  8*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  2*seq.pltq THEN seq.ceiling
                    -- if more than a pallet use the target price 
                    ELSE  seq.ceiling * 1.05
                    END END END
                ELSE
                    CASE WHEN pricegroup ~ '(Hanger|Dish)' THEN
                        --at least 1 pallets is lower limit
                        CASE WHEN qtyord >= 01*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  0.5*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling 
                        END END
                    ELSE 
                        --at least 8 pallets is lower limit
                        CASE WHEN qtyord >= 08*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  2*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --at least 1 pallet is upper range
                        ELSE CASE WHEN qtyord >=  1*seq.pltq THEN seq.ceiling
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling * 1.15
                        END END END
                    END
            END
        ELSE 
            null 
        END,5) guid
    FROM 
        ngrp grp
        LEFT OUTER JOIN nseq seq ON 
            seq.ship_dba = grp.shipgrp
            AND seq.bill_dba = grp.account
            AND seq.part = grp.part
            AND seq.rn = 1
        LEFT OUTER JOIN rlarp.repc r ON 
            r.rcode = grp.dsm
)
,orphans AS (
    SELECT
         account
        ,shipgrp
        ,chan
        ,dsm
        ,director
        ,lu
        --,partgroup
        --,pricegroup
        ,part
        -- ,glec
        ,oseas
        ,omon
        -- ,odate 
        ,sseas
        ,smon
        -- ,sdate
        ,lbs
        ,qty 
        ,sales_usd
        ,hist_price
        ,cost_curstd_usd
        ,shiplbs
        ,floor
        ,ceiling
        ,uselimits
        ,price 
        ,avgprice
        ,pltq
        ,guid
        ,least(hist_price, price, avgprice) lowest_last
        ,least(hist_price, price, avgprice, floor) lowest_floor
    FROM 
        nguid
)
----grouped prices-------------
,pgrp AS (
	SELECT
		o.bill_dba 
		,o.ship_dba
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
		,o.part
		,o.odate
		,o.qtyord
		,i.nwht * CASE WHEN i.nwun = 'KG' THEN 2.2 ELSE 1 END lbs
		,i.mpck pltq
		,ROUND(o.sales_usd / o.qty,5) price
		,(o.pricing->>'guidance_price')::NUMERIC guidance
	    ,(o.pricing->>'floor'  )::numeric(15,5) floor        
	    ,(o.pricing->>'ceiling')::numeric(15,5) ceiling   
	    ,(o.pricing->>'uselimits')::boolean uselimits
	FROM
	 	rlarp.osm_stack o
	 	LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
	 		i.item = o.part
	WHERE 
		VERSION = 'Actual' 
		AND oseas >= 2024
		AND calc_status <> 'CANCELED' 
		AND o.fs_line = '41010'
		AND o.part <> ''
		AND substring(o.glec,1,1) <= '2'
		AND o.qty <> 0
	GROUP BY 
		o.bill_dba 
		,o.ship_dba
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
		,o.part
		,o.odate
		,o.qtyord
		,o.pounds
		,o.pallets
		,ROUND(o.sales_usd / o.qty,5)
		,i.nwht * CASE WHEN i.nwun = 'KG' THEN 2.2 ELSE 1 END
		,i.mpck
		,(o.pricing->>'guidance_price')::NUMERIC
	    ,(o.pricing->>'floor'  )::numeric(15,5)        
	    ,(o.pricing->>'ceiling')::numeric(15,5)
	    ,(o.pricing->>'uselimits')::boolean
)
----sequenced for most recent price------------
,seq AS (
	SELECT 
		 bill_dba 
		,ship_dba
		,part
		,odate
		,qtyord
		,lbs
		,pltq
		,price
		,guidance
	    ,floor        
	    ,ceiling   
	    ,uselimits
	    ,row_number() OVER (PARTITION BY bill_dba, ship_dba, part ORDER BY odate desc) rn
	    ,round(avg(price) over (PARTITION BY bill_dba, ship_dba, part),5) avgprice
	FROM 
		pgrp
)
-- SELECT * FROM seq WHERE rn = 1
,grp AS (
    SELECT 
        o.account
        ,o.shipgrp
        ,o.chan
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
        ,o.part
        ,o.glec
        ,o.oseas
        -- ,o.odate
        ,og.sortmo omon
        ,o.sseas
        -- ,o.sdate
        ,sg.sortmo smon
        -- ,o.calc_status
        ,ROUND(sum(fb_qty * lbs),5) lbs
        ,ROUND(sum(fb_qty),2) qty 
        ,ROUND(sum(fb_val_loc * r_rate),2) sales_usd
        ,ROUND(sum(fb_cst_loc_cur * c_rate),2) cost_curstd_usd
    FROM 
        rlarp.osmf o
        LEFT OUTER JOIN rlarp.gld og ON 
            o.odate BETWEEN og.sdat and og.edat
        LEFT OUTER JOIN rlarp.gld sg ON
            o.sdate BETWEEN sg.sdat and sg.edat
        LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
            i.item = o.part
    WHERE
        iter IN ('actuals','actuals_plug','copy')
        AND fs_line = '41010' 
        AND substring(o.glec,1,1) <= '2'
    GROUP BY 
        o.account
        ,o.shipgrp
        ,o.chan
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
        ,o.part
        ,o.glec
        ,o.oseas
        -- ,o.odate 
        ,og.sortmo
        ,o.sseas
        -- ,o.sdate
        ,sg.sortmo
        -- ,o.calc_status
)
,guid AS (
    SELECT
         grp.account
        ,grp.shipgrp
        ,grp.chan
        ,grp.dsm
        ,r.director
        ,grp.shipgrp||'.'||grp.dsm lu
        -- ,grp.partgroup
        -- ,grp.pricegroup
        ,grp.part
        -- ,grp.glec
        ,grp.oseas
        ,grp.omon
        -- ,grp.odate 
        ,grp.sseas
        ,grp.smon
        -- ,grp.sdate
        ,grp.lbs
        ,grp.qty 
        ,grp.sales_usd
        ,CASE WHEN round(grp.sales_usd/grp.qty,5) = 0 THEN null ELSE round(grp.sales_usd/grp.qty,5) END hist_price
        ,grp.cost_curstd_usd
        ,sum(grp.lbs) OVER (PARTITION BY shipgrp, oseas, dsm) shiplbs
        ,CASE WHEN seq.floor = 0 THEN null else seq.floor END floor
        ,CASE WHEN seq.ceiling = 0 THEN null else seq.ceiling END ceiling
        ,seq.uselimits
        ,seq.price 
        ,seq.avgprice
        ,seq.pltq
        ,ROUND(CASE WHEN seq.uselimits THEN 
            CASE 
                WHEN glec = '1NU' THEN
                    --if more than 8/24 pallets, use floor
                    CASE WHEN grp.qty >= 24*seq.pltq THEN seq.floor
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  8*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  2*seq.pltq THEN seq.ceiling
                    -- if more than a pallet use the target price 
                    ELSE  seq.ceiling * 1.05
                    END END END
                ELSE
                    CASE WHEN pricegroup ~ '(Hanger|Dish)' THEN
                        --at least 1 pallets is lower limit
                        CASE WHEN qtyord >= 01*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  0.5*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling 
                        END END
                    ELSE 
                        --at least 8 pallets is lower limit
                        CASE WHEN qtyord >= 08*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  2*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --at least 1 pallet is upper range
                        ELSE CASE WHEN qtyord >=  1*seq.pltq THEN seq.ceiling
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling * 1.15
                        END END END
                    END
            END
        ELSE 
            null 
        END,5) guid
    FROM 
        grp
        LEFT OUTER JOIN seq ON 
            seq.ship_dba = grp.shipgrp
            AND seq.bill_dba = grp.account
            AND seq.part = grp.part
            AND seq.rn = 1
        LEFT OUTER JOIN rlarp.repc r ON 
            r.repp = grp.dsm
)
,baseline AS (
    SELECT
         account
        ,shipgrp
        ,chan
        ,dsm
        ,director
        ,lu
        --,partgroup
        --,pricegroup
        ,part
        -- ,glec
        ,oseas
        ,omon
        -- ,odate 
        ,sseas
        ,smon
        -- ,sdate
        ,lbs
        ,qty 
        ,sales_usd
        ,hist_price
        ,cost_curstd_usd
        ,shiplbs
        ,floor
        ,ceiling
        ,uselimits
        ,price 
        ,avgprice
        ,pltq
        ,guid
        ,least(hist_price, price, avgprice) lowest_last
        ,least(hist_price, price, avgprice, floor) lowest_floor
    FROM 
        guid
)
SELECT * FROM baseline
UNION ALL
SELECT * FROM orphans
