mysql 返回每种类型至少有一个帐户的客户的查询

xpcnnkqh  于 2022-10-31  发布在  Mysql
关注(0)|答案(1)|浏览(142)

我正在做这个关于SQL的问题:编写一个查询,返回至少拥有一个支票帐户和一个储蓄帐户的客户所拥有的支票(类型chq)和储蓄(类型sav)帐户的客户ID、类型、帐号和余额,顺序为客户ID、类型、帐号。
以下是架构:

Account = {accNumber, type, balance, branchNumberBranch}
Owns = {customerIDCustomer, accNumberAccount}
Transactions = {transNumber, accNumberAccount, amount}
Employee = {sin, firstName, lastName, salary, branchNumberBranch}
Branch = {branchNumber, branchName, managerSINEmployee, budget}

以下是我目前得到的结果:

FROM Customer C1, Owns O1, Account A1
WHERE C1.customerID = O1.customerID AND O1.accNumber = A1.accNumber
AND A1.type = 'chq' 
UNION
SELECT C2.customerID, A2.type, A2.accNumber, A2.balance
FROM Customer C2, Owns O2, Account A2
WHERE C2.customerID = O2.customerID AND O2.accNumber = A2.accNumber
AND A2.type = 'sav' 
ORDER BY customerID, type, accNumber

但是当我使用UNION时,查询只返回具有两种类型帐户的客户,而不是每种类型至少有一个帐户。
输出示例:

customerID  type accNumber   balance
----------- ---- ----------- ---------------------------------------
10839       CHQ  15          78226.03
10839       CHQ  296         65875.84

此客户有2个帐户,但都是CHQ类型。
我也试过INTERSECT,但是一个账户不能同时是两种类型。在这种情况下我该怎么办?

qaxu7uf2

qaxu7uf21#

返回客户ID ..由至少拥有一个支票帐户和一个储蓄帐户的客户拥有

SELECT customer.customer_id, ...
FROM customer JOIN account ...
GROUP BY customer.customer_id
HAVING SUM(account.type = 'chequing')
   AND SUM(account.type = 'savings')

SELECT customer.customer_id, ...
FROM customer JOIN account ...
WHERE account.type IN ('chequing', 'savings') ...
GROUP BY customer.customer_id
HAVING COUNT( DISTINCT account.type) = 2

相关问题