2011-03-22 70 views
0

我有以下查詢:問題與子查詢

  1. 的packgae的狀態必須爲「出貨:

    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) 
    

    該查詢基於以下條件軟件包表選擇包詳細信息「(通過將PACKAGE_STATISTICS的PACKAGESTATUS列設置爲2來表示)

  2. 如果包中有多個」發貨「條目,請選擇最新的(基於CREATIONDATE列值)。

當我運行上面的查詢時,它拋出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發貨日期無效的。 請讓我知道我該怎麼做? 感謝大家, Pradeep

回答

0

如果您只需要來自PACKAGE_STATISTICS的最新日期,爲什麼不簡單使用MAX(CREATION_DATE)?與最新的creationdate

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

喜Marcin,感謝您的回覆......我需要每個包裝的最大出貨日期。即,每個包將在PACKAGE_STATISTICS表中包含零個或多個已發貨狀態條目。如果沒有對應於包的「發貨」狀態條目,我不希望在結果集中包含該包。否則,我只需要最近添加的「發貨」條目 – Pradeep 2011-03-22 10:35:24

+0

因此(如果我沒有製作任何語法錯誤)我的第一個查詢應該返回你想要的。 – 2011-03-22 11:04:23

+0

事實上,你的第二個查詢確實有效。在真實場景中,我必須獲取超過20個連接8個表格的列。所以,我選擇了第二個。非常感謝你.. :) – Pradeep 2011-03-23 08:08:34