我想查询财富少于首富财富一半的人。所以我想出了以下查询:
select P.name
from
(select sum(B.balance) / 2 as Balance
from Person P1, BankAccount B, AccountOf A
where P.id = A.person_id and A.account_id = B.id
group by P1.id) as X, Persons P, BankAccount B, AccountOf A
where
group by P.id
having sum(B.balance) < max(X.Balance)
有人可以向我解释我做错了什么吗?在我看来,正常查询中出了点问题,因为单独执行的子查询给出了正确的数量。
答案 0 :(得分:1)
“查询财富少于最富有者财富一半的人”
select id,Name
from (
select
P.id,P.Name
sum(B.balance) as Balance,
max(sum(B.balance)) over() richestbalance
from
Person P
join BankAccount B on P.id = A.person_id
join AccountOf A on A.account_id = B.id
group by P.id,P.Name
) t
where Balance < richestbalance / 2
然后使用您的查询:
select P.name
from
(select sum(B.balance) as Balance
from Person P1, BankAccount B, AccountOf A
where P.id = A.person_id and A.account_id = B.id
group by P1.id) as X, Persons P, BankAccount B, AccountOf A
where ...
group by P.id
having sum(B.balance) < max(X.Balance)/2