我试图找出如何从另一个表中更新一个表,这是PL / SQL查询的结果。
这是我尝试做的事情:
update c
set c.customerType = n.newType
from customers c
join
(select
c.customerNumber, c.customerType,
case when c.customerType = 'business' and count(s.subCode) = 1
then 'small business'
else null
end as NewType
from customers c
join subscribers s on c.customerNumber = s.customerNumber
group by c.customerNumber, c.customerType) n on c.customerNumber = n.customerNumber;
请注意,表客户如下所示:
customerNumber customerType
------------------------------
1 business
4 business
2 private
3 private
表n(子查询)给出以下结果:
customerNumber customerType newType
1 business null
4 business small business
3 private null
2 private null
我在做什么错了?
P.S最终,我只想在newType不为null的情况下用newType更新customerType。
谢谢
答案 0 :(得分:1)
尝试这样
UPDATE customers
SET customerType = ( SELECT N.newType
FROM
(
SELECT c.customerNumber, c.customerType, CASE WHEN c.customerType = 'business' AND count(s.subCode) = 1 THEN 'small business' ELSE NULL END AS NewType
FROM customers c1 JOIN subscribers s ON c1.customerNumber = s.customerNumber
GROUP BY c1.customerNumber, c.customerType
) N
);
答案 1 :(得分:0)
you to write plsql like below
=============================
declare
cursor c1 is
select c.customerNumber, c.customerType,
case when c.customerType = 'business' and count(s.subCode) = 1 then 'small
business'
else null end as NewType
from customers c,subscribers s
where c.customerNumber = s.customerNumber
group by c.customerNumber, c.customerType;
begin
for cur in c1 loop
update customers set customer_type = cur.NewType
where customerNumber = cur.customerNumber;
commit;
end loop;
end;
答案 2 :(得分:0)
您使用相关子查询。不过,就您的情况而言,我认为所有工作都可以在外部where
子句中完成:
update customers c
set c.customerType = 'small business'
where c.customerType = 'business' and
(select count(s.subcode)
from subscribers s
where s.customerNumber = c.customerNumber
) = 1;
如果客户在subcode
表中恰好有一个subscribers
,则会将“业务”客户更新为“小型企业”。