AS set NOCOUNT ON;
IF OBJECT_ID('tempdb..#programWithAncestor') IS NOT NULL DROP TABLE #programWithAncestor
			 SELECT * INTO #programWithAncestor 
			 FROM   fGetProgram_Ancestor_Aliases (NULL)
	

SELECT  
        pa.ProgramName, 
        IdmsSubschemaRecords.RecordName, 
        Statements.Description AS [Statement type], 
        Count(OccurrencesStmt.OccurID) AS Expr1, pa.AncestorName, pa.ProgramID, pa.AncestorID 
FROM (((StatementReference INNER JOIN OccurrencesStmt 
                            ON StatementReference.OccurID = OccurrencesStmt.OccurID) 
          INNER JOIN #programWithAncestor pa 
		  ON OccurrencesStmt.ProgID = pa.ProgramID) 
          INNER JOIN Statements ON StatementReference.StatementType = Statements.StatementType) 
          INNER JOIN IdmsSubschemaRecords ON StatementReference.ResourceID = IdmsSubschemaRecords.ID 
WHERE (((StatementReference.ResourceType)=77)) 
GROUP BY pa.AncestorName, pa.ProgramName, IdmsSubschemaRecords.RecordName, Statements.Description, pa.ProgramID, pa.AncestorID 
ORDER BY pa.AncestorName, pa.ProgramName, pa.ProgramID, IdmsSubschemaRecords.RecordName