Select USL_OK,DS1,Count(*),SUM(SUMP),SUM(SUMP)/COUNT(*) cena From
(
Select USL_OK,Substr(DS1,1,3) DS1,SUMP 
from MTR.S19_SL Sl,MTR.S19_ZAP Z
Where Z.ID_ZAP=SL.ID_ZAP and (Substr(DS1,1,3)='O02' or Substr(DS1,1,3) between 'O04' and 'O07') and Z.SumP>0 and Z.usl_ok<3 and
Z.code in (Select code from mtr.s19_schet where Year>=$SY$ and Month >=$SM$ and Year<=$EY$ and Month <= $EM$)
)
Group by DS1,USL_OK
