Select SMO_OKATO,N,SUM(c) Sluch,Count(Distinct ENP) Lic, Sum(P) ST From ( 
select 
case when U.Code_Usl in ('U012','U052') then 1 
     when U.Code_Usl in ('U009','U053') then 2  
     when U.Code_Usl in ('U054','U055','U056','U057','U058','U059','U060','U061','U062','U063','U064') then 3  
     when U.Code_Usl in ('U065','U066','U067','U068','U069') then 4  
     when U.Code_Usl in ('U070','U071','U072','U073','U074','U075') then 5  
     when U.Code_Usl in ('U076','U077','U078','U079','U080','U081') then 6 Else Null end N,
1 C,
(select ZP_ENP from MTR.L19_ZAP@COD.LINC Z where Z.CODE=U.CODE and Z.N_ZAP=U.N_ZAP) ENP,
(select ZP_HD_1 from MTR.L19_ZAP@COD.LINC Z where Z.CODE=U.CODE and Z.N_ZAP=U.N_ZAP) SMO_OKATO,

U.SUMV_USL  P
from MTR.L19_USL@COD.LINC U Where (U.Code,U.N_ZAP,U.IDCASE) in
(Select Z.Code,Z.N_ZAP,Z.IDCASE From MTR.L19_SCHET@COD.LINC S, MTR.L19_ZAP@COD.LINC Z Where s.Year>=$SY$ and s.Month >=$SM$ and s.Year<=$EY$ and s.Month <= $EM$ and Z.Code=S.CODE and z.usl_ok=3 and Z.SUMP>0)
)
where N is not null
Group by SMO_OKATO,N
