SELECT T0.[DocDate], T0.DocNum,T0.[CardCode], T0.[CardName], T7.[descript] [Territory],
T5.[SlpName], T1.[ItemCode],
T1.[Dscription], T1.[Quantity], T1.[LineTotal], T1.[TotalFrgn],
T1.[Rate],T2.[U_SheetTab], T2.[U_SubCategory], T2.U_SPCatgry, T6.U_CatName, T3.[QryGroup22] Exports
FROM OINV T0
RIGHT JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry
INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
INNER JOIN OCRD T3 ON T0.CardCode = T3.CardCode
INNER JOIN CRD1 T4 ON T3.CardCode = T4.CardCode
INNER JOIN OSLP T5 ON T0.SlpCode = T5.SlpCode
INNER JOIN [@NCM_PRODCATGRY] T6 ON T2.U_SPCatgry = T6.U_CatCode
INNER JOIN [OTER] T7 ON T3.Territory = T7.territryID
WHERE T0.DocType ='I'
and T1.[ItemCode] = T2.[ItemCode]
AND T4.ADRESTYPE='S'
and (T2.U_SPCatgry = '079' or T2.U_SPCatgry = '168' or T2.U_SPCatgry = '169')
--and T3.[QryGroup22]= 'Y'
and T0.[DocDate] between '[%0]' and '[%1]'
Union All
SELECT T0.[DocDate], T0.DocNum, T0.[CardCode], T0.[CardName],T7.[descript] [Territory],
T5.[SlpName], T1.[ItemCode], T1.[Dscription],
(T1.[Quantity] * -1 )Quantity, (T1.[LineTotal] * -1 )LineTotal, (T1.[TotalFrgn] * -1) TotalFrgn,
T1.[Rate],T2.[U_SheetTab], T2.[U_SubCategory], T2.U_SPCatgry, T6.U_CatName , T3.[QryGroup22] Exports
FROM ORIN T0
RIGHT JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry
INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
INNER JOIN OCRD T3 ON T0.CardCode = T3.CardCode
INNER JOIN CRD1 T4 ON T3.CardCode = T4.CardCode
INNER JOIN OSLP T5 ON T0.SlpCode = T5.SlpCode
INNER JOIN [@NCM_PRODCATGRY] T6 ON T2.U_SPCatgry = T6.U_CatCode
INNER JOIN [OTER] T7 ON T3.Territory = T7.territryID
WHERE T1.[ItemCode] = T2.[ItemCode]
and T0.DocType ='I'
AND T4.ADRESTYPE='S'
and (T2.U_SPCatgry = '079' or T2.U_SPCatgry = '168' or T2.U_SPCatgry = '169')
--and T3.[QryGroup22]= 'Y'
and T0.[DocDate] between '[%0]' and '[%1]'
--However in this query even if the invoice has many items, only items belonging to U_SPCatgry 079 or 168 or 169 are displayed. This can be a problem since the commission payable has to be calculated on all the 10 items that may also belong to some other U_SPCatgry