select t.faccountstatus, sum(t.fcount) as fcount
from (
         select t.faccountstatus, count(faccountstatus) fcount
         from (
                  select case
                             when t3.fenddate >= GETDATE() then '已付费'
                             else '未付费' end as faccountstatus
                  from tagents t1
                           left join (select max(tpayinfoid) tpayinfoid, siteid, tagentsid
                                      from tpayinfo
                                      group by siteid, tagentsid) t2
                                     on t1.siteid = t2.siteid and t1.tagentsid = t2.tagentsid
                           left join tpayinfo t3
                                     on t2.siteid = t3.siteid and t2.tagentsid = t3.tagentsid and
                                        t2.tpayinfoid = t3.tpayinfoid
                  where t1.siteid = $siteid$
                  union all
select case
           when exists(select tagentsid from tuserrequestlog where siteid = t1.siteid and tagentsid = t1.tagentsid)
               then '已使用'
           else '未使用' end as faccountstatus
from tagents t1
where t1.siteid = $siteid$
    ) t
group by t.faccountstatus
union all
select '未付费', 0
union all
select '已付费', 0
union all
select '已使用', 0
union all
select '未使用',
       0 )t
group by faccountstatus
order by case when faccountstatus='已付费' then 1 when faccountstatus='未付费' then 2 when faccountstatus='已使用' then 3 when faccountstatus='未使用' then 4
end