SELECT buy.nomenclature_id,
SUM ( buy.summa )
- (SELECT ISNULL(SUM( sale.summa ),0)
FROM sale WHERE sale. nomenclature_id = buy. nomenclature_id)
FROM buy
GROUP BY buy.nomenclature_id
UNION
SELECT nomenclature_id, - SUM(summa)
FROM sale
GROUP BY nomenclature_id
HAVING (NOT (nomenclature_id IN (SELECT DISTINCT nomenclature_id FROM buy)))
WITH amount AS
(
SELECT buy.nomenclature_id, sum(buy.summa) as summa
FROM buy
GROUP BY buy.nomenclature_id
UNION ALL
SELECT sale.nomenclature_id, -1*sum(sale.summa) as summa
FROM sale
GROUP BY sale.nomenclature_id
)
SELECT nomenclature_id, sum(summa) as summa
FROM amount
GROUP BY nomenclature_id