不仅如此

时间:2012-12-27 19:14:58

标签: mysql

查找Brackendale分行贷款金额超过所有贷款的所有客户的姓名。

这可以吗?

Use University;

SELECT customer_name, loan_number
FROM loan NATURAL JOIN customer
HAVING MAX(amount) > ALL (SELECT sum(loan.amount)
FROM loan 
WHERE branch_name = 'Brakendale');

2 个答案:

答案 0 :(得分:3)

ALL是一个不需要的关键字 - 它不会执行任何操作,因为它是一个集合的默认关键字(另一个关键字为ANY)。

离开ALL会更直接。但是你可能想要一个组在那里并删除loan_number,否则每一行必须在它自己的组中。

这个查询对我来说似乎更有意义:

SELECT customer_name, MAX(amount)
FROM loan
NATURAL JOIN customer
GROUP BY customer_name
HAVING MAX(amount) > (
  SELECT sum(loan.amount)
  FROM loan 
  WHERE branch_name = 'Brakendale');

答案 1 :(得分:0)

您可能需要MAX而不是SUM在另一个方向:

SELECT customer_name, loan_number
FROM loan NATURAL JOIN customer
HAVING SUM(amount) > (SELECT max(loan.amount)
                      FROM loan 
                      WHERE branch_name = 'Brakendale'
                     );

这将是“总贷款总额超过Brakendale最大贷款的所有客户”。您的查询更像是“所有客户的贷款总额大于Brakendale所有未偿还贷款的总和”。

您甚至可能想要“所有客户的未偿还贷款都大于Brakendale的任何客户”。这将是:

SELECT customer_name, loan_number
FROM loan NATURAL JOIN customer
HAVING SUM(amount) > (SELECT max(l.CustomerLoans)
                      from (select customerID, sum(l.amount) as CustomerLoans
                            FROM loan l
                            WHERE branch_name = 'Brakendale'
                            group by customerID
                           ) l
                     );