这是家庭作业问题。
Customer(customer_id, customer_name, address, phone)
Account(bank_name, account_num, balance)
Has-Account(customer_id, bank_name, account_num)
我正在尝试为每个客户写一个光标,返回客户的ID,姓名,电话号码,银行名称以及每个银行客户帐户的总和。
CURSOR cust_balance IS
SELECT
我尝试了什么:
Select customer_id, customer_name, phone, bank_name, count(account_num) over (partition by bank_name) from Customer,
Account , Has-Account where Customer.customer_id = Has-Account.customer_id
AND Account.account_num = Has-Account.account_num and Account.bank_name = Has-Account.bank_name
如何在此查询中计算每个银行客户帐户的总和?
答案 0 :(得分:0)
要使用游标,您需要声明一个变量来存储您感兴趣的每个字段。虽然这是可能的,但使用聚合函数,按customer_id分组和某些银行字段可能更容易。您是否已经尝试过,或者分配是否严格要求使用游标。一般来说,在SELECT中处理这种操作比使用游标脚本更好。
我相信以下代码应该适合您,但我没有可用的数据库引擎来测试它。你当然可以在w3学校使用SUM函数查找,但我相信这对大多数SQL平台都很常见:
SELECT
C.customer_name,
A.bank_name,
SUM(a.balance) AS 'balance'
FROM Customer AS c
INNER JOIN Has-Account AS ha ON c.customer_id = ha.customer_id
INNER JOIN Account AS a ON (
ha.bank_name = a.bank_name AND ha.account_num = a.account_num
)
GROUP BY C.customer_id