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 
        IdmsSubschemaSets.SetName, 
        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 IdmsSubschemaSets ON StatementReference.ResourceID=IdmsSubschemaSets.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=78
            AND (IdmsSubschemaSets.SetName in (Select * from #string_param_temp))
          )   
    GROUP BY IdmsSubschemaSets.SetName, p.AncestorName, p.ProgramName, Paths.PathStr, Statements.Description 
    ORDER BY IdmsSubschemaSets.SetName, p.AncestorName, p.ProgramName, Paths.PathStr