WITH
grp AS (
	SELECT
		o.bill_dba 
		,o.ship_dba
		,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.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
)
,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 
		grp
)
SELECT * FROM seq WHERE rn = 1
SELECT 

FROM 
    rlarp.osm
