子查询问题

时间:2011-03-22 08:18:20

标签: sql oracle plsql plsqldeveloper

我有以下查询:

SELECT  SP.PACKAGEID,SP.ORDERID,PTS.CREATIONDATE AS SHIPPEDDATE

FROM PACKAGES SP

INNER JOIN 

(
SELECT * FROM 
(
    SELECT *FROM PACKAGE_STATISTICS A 
    WHERE((A.PACKAGEID=SP.PACKAGEID)
    AND(A.PACKAGESTATUS=2)
    AND(TO_DATE(to_char(A.CREATIONDATE,'mm/dd/yyyy'),'mm/dd/yyyy') 
         BETWEEN TO_DATE('2/19/2011','mm/dd/yyyy') AND (TO_DATE('3/21/2011','mm/dd/yyyy'))))
    ORDER BY A.CREATIONDATE



) WHERE ROWNUM<2

) PTS ON PTS.PACKAGEID=SP.PACKAGEID
WHERE SP.ISSUEID IN(402783)

此查询根据以下条件从PACKAGES表中选择包详细信息:

  1. packgae的状态必须为“Shipped”。(通过将PACKAGESTATUS列PACKAGE_STATISTICS设置为2表示)
  2. 如果包中有多个“已发货”条目,请选择最新(基于CREATIONDATE列值)。
  3. 当我运行上面的查询时,它会抛出ORA-00904错误,因为级别2的子查询会刷新表名。所以我修改了下面给出的查询:

    SELECT  SP.PACKAGEID,SP.ORDERID, (SELECT CREATIONDATE FROM 
    
    (
            SELECT *FROM PACKAGE_STATISTICSA 
            WHERE
    ((A.PACKAGEID=SP.PACKAGEID)
             AND(A.PACKAGESTATUS=2)
             AND(TO_DATE(to_char(A.CREATIONDATE,'mm/dd/yyyy'),'mm/dd/yyyy') 
                 BETWEEN TO_DATE('2/19/2011','mm/dd/yyyy') AND (TO_DATE('3/21/2011','mm/dd/yyyy'))))
            ORDER BY A.CREATIONDATE
        ) WHERE ROWNUM<2) AS SHIPPEDDATE
    FROM PACKAGESSP
    WHERE 
    (SHIPPEDDATE BETWEEN TO_DATE('2/19/2011','mm/dd/yyyy') 
        AND (TO_DATE('3/21/2011','mm/dd/yyyy'))) 
        AND   SP.ISSUEID IN(402783) 
    

    它再次抛出了ORA-00904 SHIPPEDDATE无效的标识符。  请让我知道我该怎么做? 感谢大家, 普拉迪普

1 个答案:

答案 0 :(得分:0)

如果您只需要PACKAGE_STATISTICS的最新日期,为什么不简单地使用MAX(CREATION_DATE)?我现在无法测试它,但您可能需要这样的查询:

SELECT SP.PACKAGEID
      ,SP.ORDERID
      ,MAX(A.CREATIONDATE) AS SHIPPEDDATE
  FROM PACKAGES SP
 INNER JOIN PACKAGE_STATISTICS A ON A.PACKAGEID = SP.PACKAGEID
 WHERE SP.ISSUEID IN (402783)
   AND A.PACKAGEID = SP.PACKAGEID
   AND A.PACKAGESTATUS = 2
   AND TO_DATE(to_char(A.CREATIONDATE, 'mm/dd/yyyy'), 'mm/dd/yyyy') BETWEEN
       TO_DATE('2/19/2011', 'mm/dd/yyyy') AND
       TO_DATE('3/21/2011', 'mm/dd/yyyy')
 GROUP BY SP.PACKAGEID
         ,SP.ORDERID

如果您想从package_statistics行获取更多详细信息,请考虑使用分析函数:

SELECT SP.PACKAGEID
      ,SP.ORDERID
      ,PTS.*
  FROM PACKAGES SP
 INNER JOIN (SELECT ROW_NUMBER() OVER(PARTITION BY PACKAGEID ORDER BY CREATIONDATE DESC) rn
                   ,A.*
               FROM PACKAGE_STATISTICS A
              WHERE A.PACKAGESTATUS = 2
                AND TO_DATE(to_char(A.CREATIONDATE, 'mm/dd/yyyy')
                           ,'mm/dd/yyyy') BETWEEN
                    TO_DATE('2/19/2011', 'mm/dd/yyyy') AND
                    TO_DATE('3/21/2011', 'mm/dd/yyyy')) PTS ON PTS.PACKAGEID =
                                                               SP.PACKAGEID
                                                           AND PTS.RN = 1;