我遇到了类似的问题,I had a couple of months ago:我需要从子查询中返回一个值,该子查询可能会也可能不会返回值列表。因此,我首先应用ORDER BY
并选择带有WHERE ROWNUM=1
的最顶层条目然后(是的,我在Oracle上)。
问题是,由于嵌套,内部查询中所需的ID未知。
上次,我被建议使用Oracles分析函数并应用MIN()
/ MAX()
。但是,这次我选择货币符号(VARCHAR
)并且无法使用这些功能。
非常感谢任何帮助。这是我的查询的相关部分:
SELECT
MyOtherColumn,
(SELECT CurrencySymbol FROM (
SELECT DISTINCT P2.ID, P2.VALIDFROMDATE, CURR.CURRENCYSYMBOL AS CurrencySymbol FROM MY_ORDER_TABLEPOS OP2
JOIN MY_ORDER_TABLE O2 ON OP2.FK_ORDER=O2.ID
JOIN MY_PRICE_TABLE P2 ON OP2.FK_CONCRETARTICLE=P2.FK_ARTICLE
JOIN MY_CURRENCY_TABLE CURR ON P2.FK_CURRENCY=CURR.ID
WHERE OP2.FK_ORDER=O.ID AND P2.ID=( -- This fails, since O.ID is unknown in inner query!
-- Determine current price for article
SELECT MAX(P3.ID) KEEP (DENSE_RANK FIRST ORDER BY P3.MINTOORDER DESC, P3.VALIDFROMDATE DESC) CurrentPriceId
FROM MY_PRICE_TABLE P3
WHERE P3.FK_ARTICLE=OP2.FK_CONCRETARTICLE
AND P3.VALIDFROMDATE<=SYSDATE
AND P3.MINTOORDER<=OP2.AMOUNT
)
ORDER BY P2.VALIDFROMDATE DESC
)
WHERE ROWNUM=1) CurrencySymbol
FROM ...
WHERE O.ID=786;
向内部查询添加ID
SELECT DISTINCT P2.ID, P2.VALIDFROMDATE, CURR.CURRENCYSYMBOL AS CurrencySymbol FROM MY_ORDER_TABLEPOS OP2
JOIN MY_ORDER_TABLE O2 ON OP2.FK_ORDER=O2.ID
JOIN MY_PRICE_TABLE P2 ON OP2.FK_CONCRETARTICLE=P2.FK_ARTICLE
JOIN MY_CURRENCY_TABLE CURR ON P2.FK_CURRENCY=CURR.ID
WHERE OP2.FK_ORDER=786 AND P2.ID=( -- ID was set statically here
-- Determine current price for article
SELECT MAX(P3.ID) KEEP (DENSE_RANK FIRST ORDER BY P3.MINTOORDER DESC, P3.VALIDFROMDATE DESC) CurrentPriceId
FROM MY_PRICE_TABLE P3
WHERE P3.FK_ARTICLE=OP2.FK_CONCRETARTICLE
AND P3.VALIDFROMDATE<=SYSDATE
AND P3.MINTOORDER<=OP2.AMOUNT
)
ORDER BY P2.VALIDFROMDATE DESC;
得到了我的结果:
ID VALIDFROMDATE CURRENCYSYMBOL
597 18.11.14 00:00:00,000000000 $
556 10.11.14 10:54:05,973000000 €
552 10.11.14 10:44:25,719000000 €
258 15.10.14 10:12:01,670000000 €
我的目标是返回最顶层条目的CURRENCYSYMBOL
(此处:$
)。
所以,我的问题是:如何将订单ID传递给嵌套查询,或者如何重写查询以满足我的需求?我知道查询过于复杂,我为此道歉。 :)
答案 0 :(得分:1)
(SELECT CurrencySymbol FROM (
SELECT OP2.FK_ORDER, CURR.CURRENCYSYMBOL AS CurrencySymbol,
ROW_NUMBER() OVER(PARTITION BY OP2.FK_ORDER ORDER BY P2.VALIDFROMDATE DESC) RW
FROM MY_ORDER_TABLEPOS OP2
JOIN MY_ORDER_TABLE O2 ON OP2.FK_ORDER=O2.ID
JOIN MY_PRICE_TABLE P2 ON OP2.FK_CONCRETARTICLE=P2.FK_ARTICLE
JOIN MY_CURRENCY_TABLE CURR ON P2.FK_CURRENCY=CURR.ID
WHERE P2.ID=(
-- Determine current price for article
SELECT MAX(P3.ID) KEEP (DENSE_RANK FIRST ORDER BY P3.MINTOORDER DESC, P3.VALIDFROMDATE DESC) CurrentPriceId
FROM MY_PRICE_TABLE P3
WHERE P3.FK_ARTICLE=OP2.FK_CONCRETARTICLE
AND P3.VALIDFROMDATE<=SYSDATE
AND P3.MINTOORDER<=OP2.AMOUNT
)
)
WHERE FK_ORDER = O.ID AND RW=1) CurrencySymbol