Got it that was a pain: sql = "select h.po, so.Ordered_Qty, so.Act_Qty totalrecieved, so.last_recv_date, " _ & " case when so.Act_Qty < Ordered_Qty or so.last_recv_date > so.Due_Date+4 then 1 " _ & " when so.Act_Qty < Ordered_Qty or so.last_recv_date IS null then 1 " _ & " else 0 " _ & " end as rating, " _ & " so.Due_Date, " _ & " d.Order_Quantity, " _ & " isnull ((select sum(nc.qty_rejected) " _ & " from K6Unipoint_Production.dbo.PT_NC nc " _ & " where nc.Origin = 'Vendor' " _
& " and nc.Origin_ref = v.vendor " if SelProgram <> "" Then sql = sql & " AND dbo.fn_GetPrgName(nc.Material) = dbo.fn_GetPrgName(so.Material) " sql = sql & " and nc.NCR_Date between '" & FromDate & "' " _ & " and '" & ToDate & "'),0) qty_rejected, " _ & " dbo.fn_GetPrgName(so.Material)program, so.Material Vendor_Reference, v.Name,v.vendor, " _ & " dbo.fn_GetVendorCat(v.Vendor) category " _ & " from PO_detail d " _ & " inner join Source so " _ & " on so.PO_Detail = d.PO_Detail " _ & " inner join PO_Header h " _ & " on d.PO = h.PO " _ & " inner join Vendor v " _ & " on h.Vendor = v.Vendor " _ & " where (dbo.fn_GetVendorCat(v.Vendor) is not null " _ & " and d.PO_Type <> 1 " _ & " and dbo.fn_GetVendorCat(v.Vendor) <> 'Unknown') " _ & " and so.Due_Date between '" & FromDate & "' and '" & ToDate & "' "