查找位于布鲁克林所有分支机构的所有客户

时间:2017-03-30 14:24:46

标签: sql database

我有一些表格:

“branch”表(branch_name,branch_city,assets)

“customer”表(customer_name,customer_street,customer_city)

“account”表(account_number,branch_name,balance)

“贷款”表(loan_number,branch_name,金额)

“存款人”表(customer_name,account_number)

“借款人”表(customer_name,loan_number)

现在,我想查找在布鲁克林所有分行拥有帐户的所有客户。这是我的SQL问题。但我想知道如何使用TABLE JOIN,并且不使用EXCEPT来解决这个问题。能有人帮我吗?谢谢。

SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))

3 个答案:

答案 0 :(得分:1)

Select A.customer_name
From depositor as A
Left join account as B
on B. account_number = A.account_number
group by A.customer_name
Having count(distinct(B.branch_name))  = 
(select count(branch_name) from branch where branch_city = 'Brooklyn')

答案 1 :(得分:1)

我无法想出使用UNION执行此操作的方法。您的问题是找到一个在布鲁克林拥有所有分支机构的客户。从根本上说,有两种方法可以解决这个问题。

  

解决方案1 ​​ - 查找的客户在布鲁克林拥有所有分支机构。

(故意双重否定)。换句话说,找到所有在布鲁克林没有至少一个分支机构的客户,然后完成其余的工作。

这就是你在你的例子中所做的。你把布鲁克林的所有分支机构EXCEPT带到了客户所拥有的分支机构,如果没有布鲁克林分支机构,那么客户就拥有了所有分支机构。您可以使用连接以另一种方式执行此操作,但您的可能性更高。

SELECT customer_name
FROM customer
WHERE customer_name NOT IN (
    SELECT d.customer_name
    FROM depositor d
    INNER JOIN branch brooklyn ON brooklyn.branch_city = 'Brooklyn'
    LEFT JOIN account a 
        ON d.account_number = a.account_number
        AND brooklyn.branch_name = a.branch_name 
    WHERE a.account_number IS NULL )
  

解决方案2 - 查找布鲁克林分店数量与布鲁克林分行数相同的所有客户。

为了做到这一点,您需要使用GROUP BY来获取每位客户的布鲁克林分行数,然后您可以使用它来与布鲁克林分行的总数进行比较。

SELECT d.customer_name
FROM depositor d
INNER JOIN account a ON d.account_number = a.account_number
INNER JOIN branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
GROUP BY d.customer_name
HAVING COUNT(DISTINCT B.branch_name) = (
    SELECT COUNT(branch_name)
    FROM branch 
    WHERE branch_city = 'Brooklyn')

UNION用于组合两个数据集。如果你的问题是......

  

"查找所有拥有布鲁克林分行帐户或贷款的客户。"

...然后你可以使用UNION

SELECT DISTINCT d.customer_name
FROM depositor d
INNER JOIN account a ON d.account_number = a.account_number
INNER JOIN branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
UNION
SELECT DISTINCT l.customer_name
FROM borrower bo
INNER JOIN loan l ON bo.loan_number = l.loan_number
INNER JOIN branch b ON l.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'

答案 2 :(得分:0)

假设您想要答案:"找到所有在布鲁克林任何分行拥有帐户的客户"

select c.*
from customer c
inner join depositor d
   on c.customer_name = d.customer_name
inner join account a
   on d.account_numver = a.account_number
inner join branch b
   on a.branch_name = b.branch_name
where b.branch_city = 'Brooklyn'

如果客户可以拥有多个帐户,或者某个帐户可以拥有多个分支,则需要调整联接。