试图找出哪家银行拥有最多的钱..
SELECT *
FROM bank B
WHERE BSB IN (SELECT max(balance)
FROM registered R, Account A
WHERE R.BSB = B.BSB
AND A.accountNumber = R.accountNumber);
答案 0 :(得分:1)
要说明问题可能有点困难,因为你没有提供发生了什么的声明,但我同意@AlexPoole将MAX(BALANCE)
与BSB
值进行比较(分支#?)可能不是你想做的。也许以下内容证明是有用的:
SELECT *
FROM bank B
WHERE BSB = (SELECT BSB
FROM (SELECT R.BSB, SUM(balance)
FROM registered R
INNER JOIN Account A
ON R.BSB = B.BSB AND
R.accountNumber = A.accountNumber
ORDER BY SUM(BALANCE) DESC)
WHERE ROWNUM = 1)
使用CTE(公用表表达式)的稍微清洁的版本可能是:
WITH BRANCH_BALANCES AS (SELECT R.BSB, SUM(balance) AS BRANCH_BALANCE
FROM BANK B
INNER JOIN registered R
ON R.BSB = B.BSB
INNER JOIN Account A
ON R.accountNumber = A.accountNumber)
SELECT *
FROM (SELECT BSB, BRANCH_BALANCE
FROM BRANCH_BALANCES
ORDER BY BRANCH_BALANCE DESC)
WHERE ROWNUM = 1
祝你好运。
答案 1 :(得分:0)
根据bank
表中的字段数量,等到最后一个可能的步骤加入它并拉出一条记录(我假设有PK或至少和Bank.BSB
上的索引。)
with balances as (
select
r.BSB, sum (a.balance) as balance_total
from
registered r,
account a
where
r.accountNumber = a.accountNumber
group by r.BSB
),
ranked_balances as (
select
BSB, balance_total,
row_number() over (order by balance_total desc) as rn
from balances
)
select
b.*
from
bank b,
ranked_balances ba
where
b.BSB = ba.BSB and
ba.rn = 1