我必须在oracle 11g中为以下场景编写一个sql查询。
我有桌子的顾客。 它有三列customer_id,cust_cat和cust_deterioration_date。 customer_id是主键。customers
(customer_id varchar2(20),
cust_cat varchar2(1),
cust_deterioration_date date
);
我有另一张表帐户。 它有4列loan_account_number,product_code,account_deterioration_date,customer_id。 loan_account_number是主键。
Accounts
(loan_account_number varchar2(20),
product_code varchar2(4),
account_deterioration_date date,
customer_id varchar2(20)
)
我必须在帐户表格中选择拥有产品代码为9213或9450且其cust_cat为' G'
的贷款帐户的客户。如果此类客户有多个包含产品代码9213或9450的贷款帐户,并且仅当所有这些贷款帐户的account_deterioration_date为空时,我应将customers表中的cust_deterioration_date更新为null。
以下是我选择所需客户的查询。
SELECT UNIQUE s1.customer_no
FROM accounts a1
,customers s1
WHERE a1.customer_id = s1.customer_no
AND NVL(s1.cust_cat,
'G') = 'G'
AND a1.product_code IN ('9213',
'9450')
AND a1.account_deterioration_date IS NULL
AND NOT EXISTS (SELECT 1
FROM accounts a
WHERE a.customer_id = s1.customer_no
AND a.account_deterioration_date IS NOT NULL
AND a.product_code IN ('9213',
'9450'))
此查询正在获取所需的结果,但代价是性能。有没有更好的方法来实现这个功能?
提前致谢
答案 0 :(得分:2)
您可以汇总每位客户的9213/9450帐户记录,并查看是否有多个条目(count(*) > 1
)且没有非null account_deterioration_dates(count(account_deterioration_date) = 0
)。使用找到的客户ID,您可以访问customers表。
update customers
set cust_deterioration_date = null
where nvl(cust_cat,'G') = 'G'
and customer_id in
(
select customer_id
from accounts
where product_code in ('9213', '9450')
group by customer_id
having count(*) > 1
and count(account_deterioration_date) = 0
);