SQL聚合子查询

时间:2021-04-21 16:18:45

标签: mysql sql function

我想查询财富少于首富财富一半的人。所以我想出了以下查询:

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) 

有人可以向我解释我做错了什么吗?在我看来,正常查询中出了点问题,因为单独执行的子查询给出了正确的数量。

1 个答案:

答案 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
相关问题