mysql - SQL 聚合子查询
问题描述
我想查询那些财富少于最富有的人一半财富的人。所以我想出了以下查询:
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)
有人可以向我解释我做错了什么,在我看来,正常查询中出现了问题,因为单独完成的子查询给出了正确的数量。
解决方案
“询问那些财富少于最富有的人一半财富的人”
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
推荐阅读
- javascript - 如何使用 jQuery 在源区域和目标区域之间移动 Draggable 对象
- java - 直接获取Base64输出,无需在desc中写入pdf
- java - Nestedscrollview 结束动画
- ubuntu - 个性化 Gitlab CE
- c# - c# - 如何将json数据存储到MySQL中
- c# - 将日期添加到日期选择器,然后将日期绑定到 Xamarin.Forms 中的 viewModel
- python - 无法从views.py 重定向
- angular - 角 6 NGRX;多重特征共享选择器
- java - 无法通过spark(2.7.7)客户端上传文件开火
- php - XMLHttpRequest 不加载jquery文件路径