【问题标题】:SQL aggregated subquerySQL 聚合子查询
【发布时间】:2021-04-21 16:18:45
【问题描述】:

我想查询那些财富少于最富有的人一半财富的人。所以我想出了以下查询:

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) 

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

【问题讨论】:

  • ANSI-92 是采用显式JOIN 语法替换隐式连接(使用, 的标准。那是非常接近30岁。请停止使用来自错误世纪的过时且容易出错的语法。这样做将帮助您在第一时间获得正确的查询,然后也更容易调试。 (例如,您在外部查询中有 no 连接谓词,如果您使用 JOIN 语法,这是不可能发生的意外。)
  • @MatBailie 感谢您的回复。我正在通过我的大学学习。不过我会调查的,谢谢。

标签: mysql sql function


【解决方案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

【讨论】:

  • 谢谢,我会试试这个。感谢您的努力!
  • 当我在大学期间这样做时,我不允许使用子查询部分,因为它会因错误使用 group 函数而出错。有没有办法像我在原始问题中尝试过的那样解决这个问题?
  • 我在查询中没有看到任何语法错误,您使用的是哪个 dbms?甚至您的查询也有一个带有 group by 的子查询
  • 您的 SQL 语法有误;检查与您的 MySQL 服务器版本相对应的手册,以在第 5 行使用“sum(B.balance) as Balance, max(sum(B.balance)) over() richestbalanc”附近的正确语法。这是我的错误我得到了,但系统可能很旧,因为来自:stackoverflow.com/questions/28835007/… 的问题来自 6 年前并且有同样的问题。 @eshirvana
  • 啊哈,你用的是哪个版本的mysql?
猜你喜欢
  • 2019-06-13
  • 2020-03-07
  • 2016-10-27
  • 1970-01-01
  • 2011-09-27
  • 2013-04-25
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多