对于以下情况,我必须在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是主键。
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为空时,我才应将客户表中的cust_deterioration_date更新为空。
这是我的查询,以选择需要的客户。
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'))
该查询正在获取所需的结果,但以性能为代价。有没有更好的方法来实现此功能?
提前致谢
您可以汇总每个客户的9213/9450帐户记录,并查看是否有多个条目(count(*) > 1
)和没有非空的account_deterioration_dates(count(account_deterioration_date) = 0
)。有了找到的客户ID,您就可以访问客户表。
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
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句