select sp.article, sum(case when trim(sp.doctype) = 'CS' then sp.quantity when trim(sp.doctype) = 'CR' then -sp.quantity end ) as quant, sum(case when trim(sp.doctype) = 'CS' then sp.totalprice when trim(sp.doctype) = 'CR' then -sp.totalprice end) as total_$ from smspec sp, smcard crd, smdocuments s where sp.doctype IN ('CS', 'CR') and s.id=sp.docid and sp.doctype = s.doctype and (s.createdat between '&date1' and '&date2') and sp.article = crd.article and crd.idclass in (select idclass from sacardclass where tree like '1.%') group by sp.article having sum(case when trim(sp.doctype) = 'CS' then sp.quantity when trim(sp.doctype) = 'CR' then -sp.quantity end ) < 5