Oracle按最大日期加入子查询

时间:2015-10-20 20:05:27

标签: sql oracle group-by cross-join

我有一个查询如下,这个查询有一个子查询得到 具有窗口函数的最大日期。此子查询的工作方式类似于没有其余查询的魅力。但随着查询的其余部分;它不会返回所需的结果。

问题是结果集具有多个具有相同CALLID的行(CALLEXSERVICESALE次数)。

查询;

SELECT DISTINCT EC.*, CESS.AUDIT_CREATE_DATE,
    LCESS.NAME
FROM ESASCASE EC
LEFT JOIN CALLMAIN CM
    ON (
            EC.CALLID = CM.CALLID
            OR EC.CALLID = - 1
            )
LEFT JOIN CALLDETAIL CD
    ON CM.CALLID = CD.CALLID
LEFT JOIN LOVCASETYPE LCT
    ON EC.LOVCASETYPEID = LCT.LOVCASETYPEID
LEFT JOIN LOVCASESTATUS LCS
    ON EC.LOVCASESTATUSCODE = LCS.LOVCASESTATUSCODE
INNER JOIN UNIT U
    ON EC.UNITID = U.UNITID
INNER JOIN UNIT U2
    ON U.PARENTUNITID = U2.UNITID
LEFT JOIN CALLCOURIER CC
    ON EC.REFERENCEID = CC.CALLCOURIERID
LEFT JOIN LOVPICKUPFAILUREREASON CNCL
    ON CC.LOVPICKUPFAILUREREASONID = CNCL.LOVPICKUPFAILUREREASONID
LEFT JOIN LOVPICKUPFAILUREREASON DLAY
    ON CC.LOVPICKUPFAILUREREASONID = DLAY.LOVPICKUPFAILUREREASONID
LEFT JOIN CALLEXSERVICESALE CESS
    ON CESS.CALLDETAILID = CD.CALLDETAILID
LEFT JOIN LOVCALLEXSALESTATUS LCESS
    ON LCESS.LOVCALLEXSALESTATUSID = CESS.LOVCALLEXSALESTATUSID
LEFT JOIN (
    SELECT d.CALLID,
        d.CALLDETAILID,
        d.AUDIT_CREATE_DATE
    FROM (
        SELECT CD.CALLID,
            CD.CALLDETAILID,
            CESS.AUDIT_CREATE_DATE,
            row_number() OVER (
                PARTITION BY CD.CALLID ORDER BY CESS.AUDIT_CREATE_DATE DESC
                ) seq
        FROM CALLDETAIL CD
        INNER JOIN CALLEXSERVICESALE CESS
            ON CD.CALLDETAILID = CESS.CALLDETAILID
        ) d
    WHERE d.seq = 1
    ) res
    ON CESS.CALLDETAILID = res.CALLDETAILID
        AND res.AUDIT_CREATE_DATE = CESS.AUDIT_CREATE_DATE
LEFT JOIN WAYBILL W
    ON W.WAYBILLID = CC.WAYBILLID
WHERE CM.AUDIT_DELETED = 0
    AND EC.LOVCASETYPEID = '7'
    AND LCS.LOVCASETYPEID = '7'
    AND EC.STARTDATE >= :pDATE1
    AND EC.STARTDATE <= :pDATE2
    AND EC.AUDIT_DELETED = 0
    AND (
        :pUNITID IS NULL
        OR U.UNITID = :pUNITID
        )
    AND (
        :pPARENTUNITID IS NULL
        OR U2.UNITID = :pPARENTUNITID
        )
    AND (
        :pCUSTOMERTYPE IS NULL
        OR DECODE(CC.ACCOUNTADDRESSID, '', 'x', 'y') = :pCUSTOMERTYPE
        )

当前结果集;

EC.*                   CESS.AUDIT_CREATE_DATE    LCESS.NAME

EC.* (same data)       20/10/2015 15:08:50       SALE CANCELLED
EC.* (same data)       20/10/2015 09:12:30       SALE COMPLETED

期望的结果集;

EC.*        CESS.AUDIT_CREATE_DATE    LCESS.NAME

EC.*        20/10/2015 15:08:50       SALE CANCELLED

其中audit_create_date是最新的。

0 个答案:

没有答案