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 
		IdmsSubschemaRecords.RecordName, 
		p.ProgramName AS ProgramName, 
		Statements.Description AS [Statement Type], 
		Count(Statements.Description) AS [Statement Count], p.AncestorName, Paths.PathStr
	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 
	LEFT JOIN ( SELECT 1 AS Flag, p1.ProgramName, p1.ProgramTypeID	FROM  #programWithAncestor p1
					GROUP BY p1.ProgramName, p1.ProgramTypeID 	  HAVING COUNT(*) > 1) f 
					on p.ProgramName = f.ProgramName and p.ProgramTypeID = f.ProgramTypeID
	LEFT JOIN dbo.Paths ON Paths.PathID = OccurrencesStmt.PathID AND f.Flag = 1
	WHERE (StatementReference.ResourceType=77
		AND (IdmsSubschemaRecords.RecordName in (Select * from #string_param_temp))
	)
	GROUP BY IdmsSubschemaRecords.RecordName, p.AncestorName, p.ProgramName, Paths.PathStr, Statements.Description 
	ORDER BY IdmsSubschemaRecords.RecordName, p.AncestorName, p.ProgramName, Paths.PathStr