0

在以下情况下,我需要一些帮助,

我有两张桌子,

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

我需要对这些表执行连接。当有多个具有相同 CONTEXT_ID(但具有不同 PACKAGE)的记录时,我需要取对应于 PACKAGE_INFO_TABLE 中最大 PACKAGE_ORDER 的行。

有人可以建议我一个方法吗?

提前致谢!

4

3 回答 3

0

以下解决方案使用两个 CTE。第一个 ( allorders) 连接两个表,而不用担心PACKAGE_ORDER. 第二个 ( maxorders) 使用先前的结果获取每个上下文 ID 的最大包顺序。主查询返回allorders谁的行CONTEXT_ID并且PACKAGE_ORDER存在于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
);

我为这个查询创建了一个小提琴

于 2014-02-28T10:34:59.000 回答
0

像这样的东西应该工作:

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)

或者这样:

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
于 2014-02-28T09:56:07.900 回答
0
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
于 2014-02-28T09:59:20.207 回答