Untitled

                Never    
SQL
       
select t.*,
	case when t.muc_tk in (1,2) then (t.so_du_dk_no + phat_sinh_no - phat_sinh_co) end as so_du_ck_co
from
(select tk.TK, tk.[TEN TAI KHOAN],  t1.muc_tk,
	ISNULL(t1.phat_sinh_no, 0 ) as phat_sinh_no,
	ISNULL(t1.phat_sinh_co, 0 ) as phat_sinh_co,
	ISNULL(cdtk.sdckn, 0 ) as so_du_dk_no, ISNULL(cdtk.sdckc, 0 ) as so_du_dk_co
 from
 TaiKhoan tk left join
 (select bang2.ma_tk, bang2.muc_tk, sum(bang2.phat_sinh_no) as phat_sinh_no, sum(bang2.phat_sinh_co) as phat_sinh_co
 from
 (select bang1.*, case when bang1.loai_tk = 'N' then bang1.st else 0 end as phat_sinh_no,
	case when bang1.loai_tk = 'C' then bang1.st else 0 end as phat_sinh_co
 from
(select taikhoan_sotien.*, RIGHT(LEFT(tkdu,2),1) as muc_tk, SUBSTRING(tkdu, 2,len(tkdu)) as ma_tk, SUBSTRING(tkdu, 1, 1) as loai_tk
		from
		(select tc.tkdu, sum(tc.st) as st
		from thuchi2015 tc
		group by tc.tkdu
		union all
		select bh.TKDU, sum(bh.ST) as st
		from banhang2015 bh
		group by bh.TKDU
		union all 
		select nh.TKDU, sum(nh.ST) as st
		from nhaphang2015 nh
		group by nh.TKDU) as taikhoan_sotien) as bang1) as bang2 
		group by bang2.ma_tk,bang2.muc_tk) as t1
	on tk.TK = t1.ma_tk
	left join CANDOITAIKHOAN cdtk on tk.TK = cdtk.tk) as t

Raw Text