用oracle中的前一个表达式替换表值

时间:2014-04-11 07:13:04

标签: sql oracle join subquery dml

好的,我有以下情况

我有一个名为employees的表,在以下情况下必须替换某些人的姓氏: 1 - 姓氏必须仅替换为在牛津工作的员工。 2 - 他们的新姓氏将成为员工编号为-1的人的姓氏(例如员工#173现在应该拥有员工#172姓氏)

这是我开始查询的方式:

select last_name,num_emp

from employees

where num_emp in(

select e.num_emp

from employees

join departments using(num_dept)

join office using(id_office)

where city='Oxford')

我做了第二个查询,以确保哪些值将替换哪个

Select last_name,num_emp

from employees

where num_emp in(

select (e.num_emp-1)

from employees

join departments using(num_dept)

join office using(id_office)

where city='Oxford')

现在我认为我可以做到这一点并使代码工作......但它没有:

update employees

set last_name=(select last_name

from employees

where num_emp in(

select (e.num_emp-1)
from employees

join departments using(num_dept)

join office using(id_office)

where city='Oxford')

收到SQL命令意外结束的错误...

所以我考虑做出改变,因为我认为在套装上有太多的价值不是重点,这就是我上次这样做的方式:

update employees

set last_name=(select last_name
from employees)

where  num_emp =(

select (e.num_emp-1)
from employees

join departments using(num_dept)

join office using(id_office)

where city='Oxford')

有一个错误,说缺少右括号,我知道它没有表达问题是什么。我知道我错过了一些东西,部分sintaxis是错误的,我可能需要打开另一个表并添加这些值以便它们被保存在那里我可以将它们与原始表进行比较,但此时我完全是被阻止,无法发现我正在做的错误。请帮助我,我真的很感激它!

2 个答案:

答案 0 :(得分:0)

您对在您的陈述中更新内容和更新内容感到困惑。

这是更新内容。我使用IN子句使它变得清晰。 EXISTS条款也是合适的。

update employees
set last_name = ...
where num_dept in
(
  select num_dept
  from departments
  where id_office in
  (
    select id_office
    from office
    where city = 'Oxford'
  )
);

以下是更新内容:

set last_name =
(
  select last_name
  from employees prev_employee
  where prev_employee.num_emp = employee.num_emp - 1
)

答案 1 :(得分:0)

您应该使用分析lag功能,然后如果员工172不存在而且您必须将员工171的名称放在173中,您还要填补空白。

您的选择应该是这样的

with new_emp as
   (select last_name,lag(last_name, 1, 0) over (order by num_emp) as new_last_name, num_emp
    from employees)
select *
from new_emp
where num_emp in(
   select e.num_emp
   from employees e
   join departments using(num_dept)
   join office using(id_office)
   where city='Oxford');

此选择将为您提供原始姓氏,新姓氏,员工编号。

然后您的更新应该是:

update employees x
set last_name = (with new_emp as
                  (select last_name,lag(last_name, 1, 0) over (order by num_emp) as new_last_name, num_emp
                   from employees)
                select new_last_name
                from new_emp ne
                where ne.num_emp = x.num_emp)
where x.num_emp in(
   select e.num_emp
   from employees e
   join departments using(num_dept)
   join office using(id_office)
   where city='Oxford');