-- UsedByProjects.sql
-- Generate summary data for projects that use this package version
--  Match control via :MATCH
--    :MATCH 0  - Match any  package name
--    :MATCH 1  - Match Package name and Project Suffix
--    :MATCH 2  - Match exactly the package. Name, Version and Suffix
 with 
  aa AS ( select NVL(v_ext,'LINK') as ext from package_versions where pv_id = :PV_ID),
  bb AS (select pkg_id from package_versions where pv_id = :PV_ID)
SELECT proj.PROJ_ID,
       proj.PROJ_NAME,
       COUNT(ev.RTAG_ID) AS USED_COUNT  
  FROM ENVIRONMENT_VIEW ev,
       PACKAGE_VERSIONS pv,
       RELEASE_TAGS rt,
       PROJECTS proj,
       aa, bb
 WHERE ev.PV_ID = pv.PV_ID
   AND ev.RTAG_ID = rt.RTAG_ID
   AND rt.PROJ_ID = proj.PROJ_ID
   AND (ev.PV_ID  = :PV_ID OR :MATCH != 2)
   AND (NVL(pv.v_ext,'LINK') in (  aa.ext ) OR :MATCH = 2 OR :MATCH = 0)
   AND (pv.PKG_ID in ( bb.pkg_id ) OR :MATCH = 2)
   AND rt.official != 'S'
GROUP BY proj.PROJ_NAME, proj.PROJ_ID
ORDER BY UPPER(proj.PROJ_NAME) ASC

