Try like this:-selectd.DocumentNumber as [Delivery number],d.ReceiptDate as [Receipt Date],tmp1.[Total Cartons],tmp2.[Total Units],tmp1.[Cartons Received],tmp2.[Units Received],tmp1.[Cartons Open]FromDocument dinner join (SELECT Document_ID, COUNT(DISTINCT c.CartonStatus_ID) as [Total Units], SUM(CASE WHEN cl.Codevalue='Carton Closed' THEN 1 ELSE 0 END) AS [Cartons Received], SUM(CASE WHEN cl.Codevalue='Carton Open' THEN 1 ELSE 0 END) AS [Cartons Open]FROM Carton c INNER JOIN codelist clON cl.Codelist_id = c.CartonStatus_IDGROUP BY Document_ID)tmp1on tmp1.Document_Id = d.Document_IdINNER JOIN (SELECT Document_ID, Sum(QtyShipped) as [Total Units], Sum(CD.QtyReceived) as [Units Received],FROM Carton c INNER JOIN CartonDetail cd on cd.Carton_Id = c.Carton_IdGROUP BY Document_ID)tmp2ON tmp2.Document_ID=d.Document_Idinner join Stores s on s.Store_Id = d.SourceIdInner join Codelist cl on cl.Codelist_id = c.CartonStatus_Idinner join dbo.Codelist cl1 on cl1.Codelist_Id = d.DocTypeleft outer join CartonDetail cd on cd.Carton_Id = c.Carton_IdLeft outer join Codelist cl2 on cl2.Codelist_Id = cd.CartonDetailType_IdWherecl.Codevalue='Carton Open'and s.StoreType =5and not d.DocumentNumber is nulland d.destinationId= 8637and cl1.CodeValue = 'JaxReceipts'and cl2.Codevalue='Carton Details'Group by DocumentNumber, d.Receiptdate,d.Document_IDOrder by DocumentNumber