AS set NOCOUNT ON;
IF OBJECT_ID('tempdb..#programWithAncestor') IS NOT NULL DROP TABLE #programWithAncestor
			 SELECT * INTO #programWithAncestor 
			 FROM   fGetProgram_Ancestor_Aliases (NULL)
			 
	SELECT DISTINCT 
    pa.ProgramName, 
    IdmsSubschemaSets.SetName, 
    Statements.Description AS [Statement type], 
    Count(Statements.Description) AS [Statement Count], 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 IdmsSubschemaSets ON StatementReference.ResourceID = IdmsSubschemaSets.ID
WHERE (((StatementReference.ResourceType)=78)) 
GROUP BY pa.AncestorName, pa.ProgramName, IdmsSubschemaSets.SetName, Statements.Description, pa.ProgramID, pa.AncestorID  
ORDER BY pa.AncestorName, pa.ProgramName, pa.ProgramID, IdmsSubschemaSets.SetName, Statements.Description