标量子查询中的子查询失败,错误为 ORA-00936 缺少表达式

Subquery within scalar subquery fails with error ORA-00936 Missing Expression

  1. 这是无效的查询:

    SELECT distinct ord.DateOrdered
       , (SELECT docno 
          FROM th_mm_c_orderline_history 
          WHERE th_mm_c_orderline_history_id 
                in (SELECT max(th_mm_c_orderline_history_id) 
                    FROM th_mm_c_orderline_history 
                    GROUP BY c_orderline_id ) 
          order by docno,c_orderline_id) as docno 
    FROM c_order ord 
    INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id 
    INNER JOIN th_mm_c_orderline_history 
          on th_mm_c_orderline_history.c_order_id=ord.c_order_id
    

    它正在向我抛出 ORA-00936 缺少表达式错误

  2. 这个查询工作正常:

    SELECT docno 
    FROM th_mm_c_orderline_history 
    WHERE th_mm_c_orderline_history_id 
          in (SELECT max(th_mm_c_orderline_history_id) 
              FROM th_mm_c_orderline_history 
              GROUP BY c_orderline_id ) 
    order by docno,c_orderline_id as docno
    

只需从内联 select 中删除 order by 子句。您不能在那里使用 order by 子句。如果需要,您可以在外部 select 中使用它...这就是您可以在没有错误的情况下完成所有这三个操作的方法:

SELECT distinct ord.DateOrdered
       , (SELECT docno FROM th_mm_c_orderline_history 
          WHERE th_mm_c_orderline_history_id 
                 in (SELECT max(th_mm_c_orderline_history_id) 
                     FROM th_mm_c_orderline_history 
                     GROUP BY c_orderline_id) 
          ) as docno 
FROM c_order ord 
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id 
INNER JOIN th_mm_c_orderline_history on th_mm_c_orderline_history.c_order_id=ord.c_order_id

您可以在整个 select 语句的末尾使用 "order by statement"。由于在select 语句中没有使用C_ORDERLINE_ID 列,所以order by 语句可能会出错。在下面试试这个版本。

 SELECT DISTINCT
       C_ORDER.DATEORDER,
       (SELECT DOCNO
          FROM TH_MM_C_ORDERLINE_HISTORY
         WHERE     C_ORDER_ID = C_ORDER_ID
               AND TH_MM_C_ORDERLINE_HISTORY_ID IN (  SELECT MAX (TH_MM_C_ORDERLINE_HISTORY_ID)
                                                        FROM TH_MM_C_ORDERLINE_HISTORY
                                                    GROUP BY C_ORDERLINE_ID)) AS DOCNO,
       C_ORDER.DOCUMENTNO
  FROM C_ORDER 
  INNER JOIN C_ORDERLINE ON C_ORDERLINE.C_ORDER_ID = C_ORDER_ID 
  ORDER BY DOCNO, C_ORDERLINE_ID;