AS set NOCOUNT ON;
IF OBJECT_ID('tempdb..#programWithAncestor') IS NOT NULL DROP TABLE #programWithAncestor
			 SELECT * INTO #programWithAncestor 
			 FROM   fGetProgram_Ancestor_Aliases (NULL)
	
SELECT p.ProgramName AS ProgramName,
 	IdmsSubschemaRecords.RecordName, 
 	Statements.Description AS [Statement type],
 	Count(OccurrencesStmt.OccurID) AS Expr1, p.AncestorName, p.ProgramID, p.AncestorID
 		FROM ((StatementReference INNER JOIN OccurrencesStmt ON StatementReference.OccurID = OccurrencesStmt.OccurID) 
		INNER JOIN #programWithAncestor p ON OccurrencesStmt.ProgID = p.ProgramID
		INNER JOIN Statements ON StatementReference.StatementType = Statements.StatementType) INNER JOIN IdmsSubschemaRecords ON StatementReference.ResourceID = IdmsSubschemaRecords.ID
 WHERE (
    ((StatementReference.ResourceType)=77) 
 	AND (p.ProgramID in (Select * from #numeric_param_temp))
 	) 
GROUP BY p.AncestorName, p.ProgramName, IdmsSubschemaRecords.RecordName, Statements.Description, p.ProgramID, p.AncestorID 
ORDER BY p.AncestorName, p.ProgramName,  p.ProgramID, IdmsSubschemaRecords.RecordName