Question

I need some assistance with the following scenario,

I have two tables,

MESSAGE_CONTEXT_TABLE (CONTEXT_ID,NAME,DESCRIPTION,PACKAGE) PK(CONTEXT_ID,PACKAGE)
PACKAGE_INFO_TABLE (PACKAGE,DESCRIPTION,PACKAGE_ORDER) PK (PACKAGE_NAME)

I need to perform a join on these tables. When there are multiple records with the same CONTEXT_ID (but with different PACKAGE) I need to take the row which corresponds to the maximum PACKAGE_ORDER in PACKAGE_INFO_TABLE.

Could somebody suggest me a way?

Thanks in advance!

No correct solution

OTHER TIPS

Something like this should work:

SELECT * 
FROM MESSAGE_CONTEXT_TABLE tm
     INNER JOIN PACKAGE_INFO_TABLE tp ON tm.package = tp.package
WHERE tp.package_order >= ALL (SELECT tp1.PACKAGE_ORDER
                               FROM MESSAGE_CONTEXT_TABLE tm1
                                    INNER JOIN PACKAGE_INFO_TABLE tp1 ON tm1.package = tp1.package
                               WHERE tm1.context_id = tm.context_id)

Or this way:

SELECT tm.*, tp.*
FROM MESSAGE_CONTEXT_TABLE tm
     INNER JOIN PACKAGE_INFO_TABLE tp ON tm.package = tp.package
     LEFT JOIN PACKAGE_INFO_TABLE tp1 ON tm.package = tp1.package
                                         AND tp1.package_order > tp.package_order
WHERE tp1.package_order IS NULL
SELECT  mct.Context_ID, MAX(pit.Package_Order)
FROM Package_Info_Table pit
INNER JOIN MESSAGE_CONTEXT_TABLE mct
ON mct.Context_ID = pit.Context_ID
AND mct.Package <> pit.package

The following solution uses two CTE. The first (allorders) joins both tables, without worrying with PACKAGE_ORDER. The second (maxorders) get the max package order for each context id using the previous result. The main query returns the rows of allorders whose CONTEXT_ID and PACKAGE_ORDER exist in maxorders:

WITH allorders AS (
  SELECT *
  FROM MESSAGE_CONTEXT_TABLE msg
  JOIN PACKAGE_INFO_TABLE    pkg ON (pkg.PACKAGE = msg.PACKAGE)
)
, maxorders AS (
  SELECT aux.CONTEXT_ID, MAX(aux.PACKAGE_ORDER) AS max_PACKAGE_ORDER
  FROM allorders aux
  GROUP BY aux.CONTEXT_ID
)
SELECT *
FROM allorders aor
WHERE EXISTS (
  SELECT 'x'
  FROM maxorders mor
  WHERE aor.CONTEXT_ID    = mor.CONTEXT_ID
    AND aor.PACKAGE_ORDER = mor.max_PACKAGE_ORDER
);

I created a fiddle for this query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top