2014-02-28 49 views
0

我需要以下情形一些援助的最高值的連接操作和過濾記錄,執行根據partucular列

我有兩個表,

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的行。

有人可以給我一個建議嗎?

在此先感謝!

回答

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 
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 
0

以下解決方案使用兩個CTE。第一個(allorders)加入這兩個表格,不用擔心PACKAGE_ORDER。第二個(maxorders)使用先前的結果獲取每個上下文ID的最大程序包順序。主要查詢返回的allordersCONTEXT_IDPACKAGE_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 
); 

我爲這個查詢創建一個fiddle

+0

這是查詢的結構?我無法運行它(儘管嘗試了不同的更改) – pragan

+0

嗨,@pragan,對不起,我沒有檢查過之前的語法。我爲它創建了一個小提琴,所以你可以添加一些數據,看看結果是否是預期的。 –

+0

thnx。但仍然無法得到我想要的查詢結果。 樣本數據, MESSAGE_CONTEXT_TABLE 'CONTEXT_ID NAME \t說明\t PACKAGE Context_1 \t Context_1 \t pkg_1 Context_1 \t Context_1 \t pkg_2 Context_3 \t Context_3 \t pkg_1 ' PACKAGE_INFO_TABLE '包裝描述PACKAGE_ORDER pkg_1 \t包1 pkg_2 \t套餐2 ' 樣品的結果集, 'CONTEXT_ID名包PACKAGE_ORDER 1 Context_1 pkg_1 2 Context_2 pkg_2 2 3 Context_3 pkg_1 1 ' 如果我們拿第一2排,我只需要那些2中的第二排 – pragan