select isnull(a.cus_id, b.cus_id) as cus_id, isnull(a.num,0) - isnull(b.numcus_id,0) as x_num from table1 as a full join table1 as b on a.cus_id = b.cus_id and b.flag = 2 where a.flag = 1
select cus_id,sum(num*(case when flag=1 then 1 else -1 end)) where flag in (1,2) group by cus_id order by cus_id asc
isnull(a.num,0) - isnull(b.numcus_id,0) as x_num
from table1 as a full join table1 as b
on a.cus_id = b.cus_id and b.flag = 2
where a.flag = 1