select t.fcostname,t.ftype, sum(t.famount) famount
from (
       select t1.fcostname,t1.ftype, t1.famount, t2.sequence
       from tagents_costmx t1
              left join ttypedetail t2 on t2.ftype = '费用项目' and t1.fcostname = t2.fvalue
       where t1.siteid =$siteid$ and t1.tagentsid=$tagentsid$ and t1.tagents_costid = $tagents_costid$
       union all
       select fvalue,ftypemx, 0, sequence
       from ttypedetail
       where ftype = '费用项目'
         and (siteid is null or (siteid =$siteid$ and fisused = 1))
     ) t
group by t.fcostname, t.sequence,t.ftype
order by t.sequence