SELECT pv.pv_id AS dpv_id, 
       sorted.build_order, 
       sorted.pkg_name,
       sorted.pkg_id
  FROM
      package_versions pv, release_content rel,
     (
     /* Remove duplicates by finding the MAX build order per package */
     SELECT DISTINCT bord.pkg_id,
             MAX(bord.build_order) OVER (PARTITION BY bord.pkg_id) AS build_order,     
             pkg.pkg_name  
      FROM packages pkg,
           (
              /* Get dependency tree limited to current release */
              SELECT dpkg_id AS pkg_id, LEVEL AS build_order
                FROM package_dependencies dep
              CONNECT BY PRIOR dpkg_id = pkg_id AND pv_id IN ( $RELPVLIST$ )
              START WITH pkg_id = $PKG_ID$ AND pv_id IN ( $RELPVLIST$ )
           ) bord
      WHERE pkg.pkg_id = bord.pkg_id
        AND bord.pkg_id <> 0
     ) sorted
 WHERE pv.pkg_id = sorted.pkg_id
   AND pv.pv_id = rel.pv_id
   AND rel.rtag_id = $RTAG_ID$
   /* AND pv.pv_id IN ( $RELPVLIST$  )   */
ORDER BY sorted.build_order ASC