SELECT

CO.Contract  "Site"

,CO.Customer_no "Customer No"

,Cust_Ord_Customer_API.Get_Name(CO.CUSTOMER_NO) "Customer Name"

,CO.Order_no "BO"

,CO.CUSTOMER_PO_NO "BO PO Number"

,COL.DESIRED_QTY "BO Desired_Qty"

,COL.BUY_QTY_DUE "BO Sales_Qty"

,H.NO "CO"

,COL2.DESIRED_QTY "CO Desired_Qty"

,COL2.BUY_QTY_DUE "CO Sales_Qty"

,COL2.CF$_REMAINING "CO Remaining_Qty"

,DECODE(COL2.CATALOG_TYPE_DB, 'INV', COL2.QTY_SHIPPED, NULL) "CO Delivered_Qty"

,C2.CUSTOMER_PO_NO "NO PO Number"

,COL.part_no "Sales Part No"

,COL.CUSTOMER_PART_NO "Cust Part No"

,C2.state "CO Status"

,C2.WANTED_DELIVERY_DATE "Wanted date"

,COL2.REAL_SHIP_DATE"Actual Ship Date"


FROM customer_order_cfv  CO

INNER JOIN customer_order_line COL ON CO.order_no = COL.order_no

inner JOIN (Select Order_No NO, SUBSTR(Message_Text, 19, 10) BO From Customer_Order_History where SUBSTR(Message_Text, 1, 17)='Copied from order') H on H.BO=CO.Order_No

inner join customer_order_cfv C2 on C2.Order_No=H.NO

INNER JOIN customer_order_line_cfv COL2 ON H.NO = COL2.order_no

Where CO.Order_id IN ('BO') and C2.state not in ('Cancelled')
and CO.Contract='&Site'
and CO.CUSTOMER_PO_NO LIKE NVL('&Contract_No','%')
and COL2.STATE not in ('Cancelled')
and COL.STATE not in ('Cancelled')