select x.*,y.qty as cn_qty, x.qty-y.qty as outstanding from
(select h.id as 'goods_received_note_id', d.item_id,sum(d.quantity) as qty from 0p4_goods_received_note h
left join 0p4_goods_received_note_detail d on d.goods_received_note_id=h.id
where h.id=241
group by d.item_id, h.id) x
left join (select h.goods_received_note_id, d.item_id,sum(d.quantity) as qty from 0p4_credit_note h
left join 0p4_credit_note_items d on d.credit_note_id=h.id
where h.goods_received_note_id=241 and d.item_id is not null
group by d.item_id) y on x.item_id=y.item_id
where x.qty > y.qty
