当我们在选择列表中使用选择查询时,我们可以使用Order By子句吗?
我想写这样的查询: -
select col1
, col2
, (select colX from table2 where table2.col1=table1.col1 and rownum<2 order by colY desc)
, (select colXX from table3 where table3.col1=table1.col1 and rownum<2 order by colYY desc)
from table1;
我不能加入这张桌子。它只是我想要的例子。
行。这就是事情。 我有以下用SQL Server编写的代码。我想将其转换为Oracle。
SELECT
BANK_ADDRESS1= (SELECT top 1 OWNER_ADDRESS1
FROM OWNER_ADDRESS OA, BANK_ACCOUNT
WHERE PAYMENT.BANK_ACCOUNT_ID = BANK_ACCOUNT.BANK_ACCOUNT_ID
and BANK_ACCOUNT.BANK_ID = OA.OWNER_ID
order by Isnull (OA.primary_addr , 'N') desc),
PAYEE_ADD1 = ( SELECT top 1 OWNER_ADDRESS1
FROM OWNER_ADDRESS OA
WHERE OA.OWNER_ID = PAYEE_OWNER.OWNER_ID
order by Isnull (OA.primary_addr , 'N') desc ),
FROM PAYMENT
inner JOIN PAYEE ON PAYMENT.PAYMENT_ID = PAYEE.PAYMENT_ID
inner join OWNER PAYEE_OWNER on PAYEE_OWNER.OWNER_ID = PAYEE.PAYEE_NAME_ID
希望这能清除我真正想要的东西。
答案 0 :(得分:2)
你想要这样的东西:
select col1,
col2,
(select colX
from (select col1, colX from table2 order by colY desc) table2
where table2.col1 = table1.col1
and rownum < 2),
(select colXX
from (select col1, colXX from table3 order by colYY desc) table3
where table3.col1 = table1.col1
and rownum < 2)
from table1;
或者这个:
select col1,
col2,
(select max(colX) keep(dense_rank last order by colY)
from table2
where table2.col1 = table1.col1),
(select max(colXX) keep(dense_rank last order by colYY)
from table2
where table2.col1 = table1.col1)
from table1;
此子选择
(select colX from table2 where table2.col1=table1.col1 and rownum<2 order by colY desc)
即使它起作用也不会返回你的预期,因为rownum是在订购之前计算的。您将从满足条件table2.col1 = table1.col1。
的那些中获得随机行尝试
select (SELECT max(OWNER_ADDRESS1) keep(dense_rank last order by nvl(oa.primary_addr, 'N'))
FROM OWNER_ADDRESS OA, BANK_ACCOUNT
WHERE PAYMENT.BANK_ACCOUNT_ID = BANK_ACCOUNT.BANK_ACCOUNT_ID
and BANK_ACCOUNT.BANK_ID = OA.OWNER_ID) bank_address1,
(SELECT max(OWNER_ADDRESS1) keep(dense_rank last order by nvl(oa.primary_addr, 'N'))
FROM OWNER_ADDRESS OA
WHERE OA.OWNER_ID = PAYEE_OWNER.OWNER_ID) payee_add1
from PAYMENT
inner JOIN PAYEE
ON PAYMENT.PAYMENT_ID = PAYEE.PAYMENT_ID
inner join OWNER PAYEE_OWNER
on PAYEE_OWNER.OWNER_ID = PAYEE.PAYEE_NAME_ID
(我本可以做一些语法错误,无法检查)。