Select dm.* , iif(dk.SL01 > 0,dk.SL01,0) +iif(pre.pssl > 0,pre.pssl,0) as SLdkBC,
iif(dk.ttien01>0,dk.ttien01,0)+ iif( pre.pstt>0,pre.pstt,0) as TTDkBC, dtps.sln,dtps.ttn, dtps.slx,dtps.ttx,
iif(SLdkBC>0,SLdkBC,0)+iif(dtps.sln>0,dtps.sln,0) - iif(dtps.slx,dtps.slx,0) as SLCky,
iif(TTDkBC>0,TTDkBC,0) + iif(dtps.ttn>0,dtps.ttn,0) - iif(dtps.ttx >0,dtps.ttx,0) as TTCky
from ( (danhmuc dm left join Ton1 dk on dm.MA_VLSPHH = dk.Ma01)
left join (select dt.MA_VLSPHH as Ma,sum(iif(dt.loai_phieu="N",dt.slg,- dt.slg)) as PSSL,
sum(iif(dt.loai_phieu="N",dt.THANH_TIEN,- dt.THANH_TIEN)) as PStt
from data dt where dt.ngay_ct < dateserial(2013,2,1) group by dt.MA_VLSPHH ) as Pre on pre.Ma=dm.MA_VLSPHH )
left join (select dt.MA_VLSPHH as Ma,sum(iif(dt.loai_phieu="N",dt.slg,0)) as sln, sum(iif(dt.loai_phieu="N",dt.THANH_TIEN,0)) as ttn,
sum(iif(dt.loai_phieu="X",dt.slg,0)) as slx, sum(iif(dt.loai_phieu="X",dt.THANH_TIEN,0)) as ttx
from data dt where dt.ngay_ct >= dateserial(2013,2,1) and dt.ngay_ct <= dateserial(2013,2,28) group by dt.MA_VLSPHH ) as dtps
on dtps.Ma=dm.MA_VLSPHH