Oracle Nested Select不允许按子句排序

时间:2019-02-26 06:29:38

标签: sql oracle oracle11g

我需要基于KSA.LEAD_ID = LRD.LEAD_ID从LEAD_REASSIGNMENT_TABLE LRD获取最新记录。 查询如下,

SELECT
KSA.LEAD_ID  AS "leadId",
KSA.CREATED_ON      AS "createdOn",
KSA.FIRST_NAME      AS "firstName",
KSA.LAST_NAME       AS "lastName",
KSA.CRN             AS "crn" ,
KSA.MOBILE_NO        AS "mobileNumber",
KSA.BRANCH_CODE     AS "lpdBranchCode", 

( SELECT T.DESCRIPTION FROM TERRITORY T WHERE T.ID IN 
    (
        SELECT STM.TERRITORY_ID FROM SPOKE_TERRITORY_MAPPING STM
         WHERE STM.SPOKE_CODE IN (SELECT SM.ID FROM SPOKE_MASTER SM WHERE SM.SPOKE_CODE=KSA.BRANCH_CODE AND SM.DELETE_FLAG='F') AND STM.DELETE_FLAG='F' 
     ) AND T.DELETE_FLAG='F' AND ROWNUM<=1
)  AS "lpdSubLocation" ,

(select lrd.LEAD_NEW_ASSIGNED_USER  from LEAD_REASSIGNMENT_DETAILS lrd
where lrd.LEAD_ID = KSA.LEAD_ID and rownum <=1
) AS "NEW_ASSIGNED_USER"


FROM KSA_LEAD_DATA KSA
   LEFT JOIN LEAD_PROSPECT_DETAILS LPD
ON KSA.LEAD_ID = LPD.KSA_LEAD_ID 
LEFT JOIN ENTITY_TYPE_MAPPING ETM
ON LPD.LOAN_STATUS = ETM.ENTITY_CODE 
    WHERE KSA.DELETE_FLAG IS NOT NULL 
  ORDER BY KSA.LEAD_ID desc ;

现在在选择“我要做”时

(select lrd.LEAD_NEW_ASSIGNED_USER  from LEAD_REASSIGNMENT_DETAILS lrd
where lrd.LEAD_ID = KSA.LEAD_ID and rownum <=1
ORDER BY LRD.MODIFIED_ON) AS "NEW_ASSIGNED_USER"

我得到ORA-00907:缺少右括号 00907. 00000-“缺少右括号” 错误

但是当我使用不按条款排序时,效果很好

(select lrd.LEAD_NEW_ASSIGNED_USER  from LEAD_REASSIGNMENT_DETAILS lrd
where lrd.LEAD_ID = KSA.LEAD_ID and rownum <=1
) AS "NEW_ASSIGNED_USER"

如果我使用select不带order by子句,则不能保证我会从LEAD_REASSIGNMENT_TABLE中获取最新记录。

注意 LEAD_REASSIGNMENT_TABLE包含3-4条具有相同Lead_id的记录 所以我要根据Modifyed_on时间戳选择最新记录。

我应该如何在嵌套select中使用Order by子句??

1 个答案:

答案 0 :(得分:0)

我不喜欢相关子查询,不在SELECT语句之内。

无论如何:如果您按如下方式重写该段代码,我想它应该可以工作。

(SELECT lrd.LEAD_NEW_ASSIGNED_USER
  FROM LEAD_REASSIGNMENT_DETAILS lrd
 WHERE     lrd.LEAD_ID = KSA.LEAD_ID
       AND lrd.modified_on = (SELECT MAX (lrd1.modified_on)
                                FROM LEAD_REASSIGNMENT_DETAILS lrd1
                               WHERE lrd1.lead_id = lrd.lead_id)) AS "NEW_ASSIGNED_USER"