SELECT
            tb_PurchaseOrder.col_PurchaseOrderID,
            tb_PurchaseOrder.col_POPrefix,
            tb_PurchaseOrder.col_PostDate,
            tb_PurchaseOrder.col_Creator,
            tb_PurchaseOrder.col_ExternalPOCreateFailure,
            tb_PurchaseOrder.col_ExternalPOCompleteFailure,
            tb_PurchaseOrder.col_VendorListCompanyID,
            tb_PurchaseOrder.col_Status,

            tb_Phase.col_ExternalPhase,

            tb_Lot.col_ExternalLot,

            tb_ListCompany.col_CompanyName,
            tb_ListCompany.col_ExternalCompanyID,

            tb_AdminTradeContractCostCodes.col_SubContractID,

            tb_PurchaseOrderItem.col_ExternalPOCreate,
            tb_PurchaseOrderItem.col_ExternalPOComplete,

            MIN(
                CASE
                    WHEN col_ExternalPOCreateFailure IS NOT NULL OR col_ExternalPOCreate IS NOT NULL THEN '1 poCreateAlreadySent'
                    WHEN col_ExternalPOCreateFailure IS NULL AND col_ExternalPOCreate IS NOT NULL THEN '2 poCreateDone'
                    WHEN col_ExternalPOCompleteFailure IS NOT NULL OR col_ExternalPOComplete IS NOT NULL THEN '3 poCompleteAlreadySent'
                    WHEN col_ExternalPOCompleteFailure IS NULL AND col_ExternalPOComplete IS NOT NULL THEN '4 poCompleteDone'
                    ELSE '5 nothing'
                END
            ) AS status

FROM        tb_PurchaseOrder

LEFT JOIN   tb_Phase
ON          tb_Phase.col_Centre =  tb_PurchaseOrder.col_Centre
AND         tb_Phase.col_Phase = tb_PurchaseOrder.col_Phase

LEFT JOIN   tb_Lot
ON          tb_Lot.col_Centre =  tb_PurchaseOrder.col_Centre
AND         tb_Lot.col_Phase = tb_PurchaseOrder.col_Phase
AND         tb_Lot.col_Lot = tb_PurchaseOrder.col_Lot

LEFT JOIN   tb_ListCompany
ON          tb_ListCompany.col_ListCompanyID = tb_PurchaseOrder.col_VendorListCompanyID

LEFT JOIN   tb_AdminTradeContractCostCodes
ON          tb_AdminTradeContractCostCodes.col_Centre =  tb_PurchaseOrder.col_Centre
AND         tb_AdminTradeContractCostCodes.col_Phase = tb_PurchaseOrder.col_Phase
AND         tb_AdminTradeContractCostCodes.col_ListCompanyID = tb_PurchaseOrder.col_VendorListCompanyID

LEFT JOIN   tb_PurchaseOrderItem
ON          tb_PurchaseOrder.col_PurchaseOrderID = tb_PurchaseOrderItem.col_PurchaseOrderID

WHERE       1
AND         tb_PurchaseOrder.col_Status NOT IN ('Open', 'Pending', 'Cancelled')
AND         tb_PurchaseOrder.col_LockedOn IS NOT NULL
AND         tb_PurchaseOrderItem.col_PurchaseOrderID IS NOT NULL
            $statusCondition
            $typeCondition
            $dateCondition
            $tradeCondition
            $failedCondition
            -- $userCondition

GROUP BY    tb_PurchaseOrder.col_PurchaseOrderID
HAVING      status != '5 nothing'

ORDER BY    tb_PurchaseOrder.col_PostDate DESC