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 AS ProgramName, 
	Count(distinct OccurrencesStmt.OccurID) AS CallCount, pa.AncestorName AS Ancestor, pa.ProgramID, pa.AncestorID
FROM (StatementReference RIGHT JOIN OccurrencesStmt ON StatementReference.OccurID = OccurrencesStmt.OccurID) 
RIGHT JOIN #programWithAncestor pa ON OccurrencesStmt.ProgID = pa.ProgramID
WHERE StatementReference.ResourceType=5 
	AND pa.OccurID<>0 
	AND pa.ProgramTypeID <> 9 
GROUP BY pa.AncestorName, pa.ProgramName, pa.ProgramID, pa.AncestorID
ORDER BY pa.AncestorName, pa.ProgramName
