select code as КОД,nametest as НАЗВАНИЕ,cena as ЦЕНА,count(*) as КОЛИЧЕСТВО,cena*count(*) as СУММАfrom ( select t3.num,t4.code,t4.nametest,t4.cena,t4.numtestgroup,t5.idissledovanie,t4.numsort from pakets t1 inner join pecientinworklist t2 inner join soderpaket t3 inner join tests t4 inner join testgroups t5 on t5.numtestgroup=t4.numtestgroup on t4.numtest=t3.numtesta on t3.idpacientinworklist=t2.id on t2.idpaket=t1.numpaket where t3.is_profile=0 and t3.numparentrecord=0 and t1.datepaket >= DDDATE1 and t1.datepaket<=DDDATE2 union select t3.num,t4.code,t4.nametest,t4.cena,t4.numtestgroup,t5.idissledovanie,t4.numsort from pakets t1 inner join pecientinworklist t2 inner join soderpaket t3 inner join tests t4 inner join testgroups t5 on t5.numtestgroup=t4.numtestgroup on t4.numtest=t3.numtesta on t3.idpacientinworklist=t2.id on t2.idpaket=t1.numpaket,soderpaket tt3 where tt3.is_profile=1 and t3.numparentrecord=tt3.num and t3.idpacientinworklist = tt3.idpacientinworklist and tt3.numparentrecord = 0 and t1.datepaket >= DDDATE1 and t1.datepaket<=DDDATE2)group by code,nametest,cena,numtestgroup,idissledovanie,numsortorder by idissledovanie,numtestgroup,numsort