/* Find Package Version */
SELECT DISTINCT pv.PKG_VERSION,
    pv.PV_ID,
    pv.DLOCKED,
    pv.MODIFIED_STAMP,
    pv.COMMENTS,
    NVL(usr.FULL_NAME, 'Unknown User') AS FULL_NAME,
    usr.USER_EMAIL,
    -- Field to assist in determining if the user can delete the version
    pv.OWNER_ID,
    pv.CREATOR_ID,
    NVL2(rc.rtag_id,1,0) as inuse,
    trunc(SYSDATE - pv.CREATED_STAMP + 0.5) as age,
    pm.code_lines,
    (CASE bi.reason WHEN 'R' THEN 'Ripple' WHEN 'N' THEN 'New Version' WHEN 'T' THEN 'Test' WHEN 'P' THEN 'Restored' WHEN 'F' THEN 'ForcedRipple' ELSE '' END ) as reason,
    bi.state,
    (select count(*) from test_run tr where tr.build_id = cbi.build_id) as test_count,
    pv.build_time,
    pln.NAME as licence,
    pv.pkg_idext,
    pv.build_type
  FROM PACKAGE_VERSIONS pv,
       USERS usr,
       RELEASE_CONTENT rc,
       ( select pv_id, max(build_id) as build_id  from BUILD_INSTANCES bi
          where bi.state in ('C')
          and bi.reason not in ('T')
          group by pv_id
        ) cbi,
       BUILD_INSTANCES bi,
       package_metrics pm,
       LICENCING pl,
       LICENCES pln
 WHERE pv.PKG_ID = :PKG_ID
   AND pv.PKG_VERSION LIKE :PKG_VERSION
   AND pv.MODIFIER_ID = usr.USER_ID(+)
   AND pv.pv_id = rc.pv_id(+)
   AND cbi.pv_id(+) = pv.pv_id
   and cbi.build_id = bi.build_id(+)
   AND pm.pv_id (+) = pv.pv_id
   and pl.PV_ID(+) = pv.pv_id
   and pln.LICENCE(+) = pl.LICENCE

