AS SELECT
   Files.LogicalName AS [File Name], 
   ProgramAliases.AliasName AS ProgramName, 
   Statements.Description AS [Statement type], 
   Count(OccurrencesStmt.OccurID) AS Expr1, Programs.Ancestor, pth.PathStr 
   , (Programs.Ancestor+ProgramAliases.AliasName) as k
FROM (
    (
        (StatementReference INNER JOIN OccurrencesStmt 
            ON StatementReference.OccurID = OccurrencesStmt.OccurID
         ) INNER JOIN Files 
           ON StatementReference.ResourceID = Files.FileID
     ) INNER JOIN Programs 
       ON OccurrencesStmt.ProgID = Programs.ProgramID
	   INNER JOIN ProgramAliases ON Programs.ProgramID = ProgramAliases.ProgramId and ProgramAliases.AliasType = 0
) INNER JOIN Statements 
  ON StatementReference.StatementType = Statements.StatementType 
  LEFT JOIN ( SELECT 1 AS Flag, AliasName, ProgramTypeID	FROM dbo.Programs  INNER JOIN dbo.ProgramAliases
		 			ON Programs.ProgramID = ProgramAliases.ProgramId and ProgramAliases.AliasType = 0
					GROUP BY AliasName, ProgramTypeID 	  HAVING COUNT(*) > 1) f 
					on ProgramAliases.AliasName = f.AliasName and Programs.ProgramTypeID = f.ProgramTypeID
  LEFT JOIN dbo.Paths pth ON pth.PathID = OccurrencesStmt.PathID AND f.Flag = 1
WHERE 
(
   ((StatementReference.ResourceType)=9)
   AND Programs.ProgramTypeID in (1, 2, 3, 10, 11, 15, 16) 
) 
GROUP BY Files.LogicalName, Programs.Ancestor, ProgramAliases.AliasName, pth.PathStr, Statements.Description 
ORDER BY Files.LogicalName, pth.PathStr, k, Statements.Description 