SELECT POFMCCompany.Company, POFMCDepartment.Departmant, c.CodePM,
(SELECT TOP (1) Machine
FROM POFMCMachine AS A
WHERE (c.CodePM = CodePM)) AS Machine,
COUNT(c.MachineID) AS count,
SUM(c.Length) AS sum
FROM POFMCCompany INNER JOIN
POFMCMachine AS b ON POFMCCompany.ID = b.IDCompany INNER JOIN
POFMCDepartment ON b.IDDepartment = POFMCDepartment.ID INNER JOIN
POFMCRepair AS c ON b.ID = c.MachineID
GROUP BY POFMCCompany.Company, POFMCDepartment.Departmant, c.CodePM
ORDER BY sum DESC