尽管使用TOP 1,子查询仍返回多行。
我一生中一直使用MS SQL,我确定以下代码可以工作,但在Oracle(NetSuite)中则行不通。
我正在尝试使用TRANSACTION_ID列将表TRANSACTIONS中的行与表SYSTEM_NOTES中的行连接起来,这样对于TRANSACTIONS中的每一行都应只返回SYSTEM_NOTES中的一行。
SYSTEM_NOTES表可能没有行,也可能没有一行或多行,而TRANSACTION_ID与TRANSACTION表中的行匹配。
查询应仅返回最新行(根据SYSTEM_NOTES表中的DATE_CREATED列确定)。
SELECT
SS.NAME AS "ENTITY NAME",
TL.TRANSACTION_ID AS "TRANSACTION INTERNAL ID",
WF.VALUE_NEW AS "APPROVED BY",
WF.DATE_CREATED AS "APPROVED DATE",
TL.AMOUNT AS "AMOUNT (entity currency)",
(CASE WHEN TL.AMOUNT_FOREIGN IS NULL THEN TL.AMOUNT ELSE TL.AMOUNT_FOREIGN END) AS "AMOUNT (original currency)",
CY.SYMBOL AS "CURRENCY CODE"
FROM TRANSACTIONS TS
LEFT OUTER JOIN ACCOUNTS AC ON TL.ACCOUNT_ID = AC.ACCOUNT_ID
LEFT OUTER JOIN ACCOUNTING_PERIODS AP ON TS.ACCOUNTING_PERIOD_ID = AP.ACCOUNTING_PERIOD_ID
LEFT OUTER JOIN
/* The following part for some entries returns more than one row despite using TOP 1 */
(SELECT TOP 1 SN.TRANSACTION_ID, SN.VALUE_NEW, SN.DATE_CREATED FROM SYSTEM_NOTES SN WHERE SN.STANDARD_FIELD = 'NEXTAPPROVER' AND SN.VALUE_NEW IS NOT NULL
ORDER BY SN.DATE_CREATED DESC)
WF ON WF.TRANSACTION_ID = TS.TRANSACTION_ID
/* End of the faulty part */
WHERE TL.AMOUNT IS NOT NULL AND TL.AMOUNT <> 0
AND TS.IS_NON_POSTING = N'No'
AND (AP.QUARTER = N'No' AND AP.YEAR_0 = N'No' AND CAST(AP.STARTING AS DATE) BETWEEN {d '2018-12-01'} AND {d '2018-12-01'})
当我单独为一个事务ID运行子查询时,我仅得到预期的1行(SYSTEM_NOTES表中有三个具有该ID的条目)。
SELECT TOP 1
SN.TRANSACTION_ID,
SN.VALUE_NEW, SN.DATE_CREATED FROM SYSTEM_NOTES SN WHERE SN.STANDARD_FIELD = 'NEXTAPPROVER' AND SN.VALUE_NEW IS NOT NULL AND SN.TRANSACTION_ID = 171954
ORDER BY SN.DATE_CREATED DESC
我也尝试了以下代码,但是row_number()部分在我的系统中似乎不起作用。
SELECT SN.TRANSACTION_ID, SN.VALUE_NEW, SN.DATE_CREATED,
ROW_NUMBER() OVER (ORDER BY SN.DATE_CREATED DESC ) AS ROW_NUM
FROM SYSTEM_NOTES SN
WHERE SN.STANDARD_FIELD = 'NEXTAPPROVER' AND SN.VALUE_NEW IS NOT NULL
AND SN.TRANSACTION_ID = 171954
答案 0 :(得分:0)
我认为您应该使用rownum
而不是TOP
。
语法:
select * from dual where /*conditions*/ and rownum = 1
我为你做了一个例子:
rownum
:row_number
: