在SQL Server中交换行值

时间:2015-09-26 18:39:23

标签: sql-server sql-server-2008

我对SQL Server有疑问

资料来源:emp

id      | name  | check |deptname 
100     |  a    |  1    |ceo   
100     |  b    |  2    |hr
100     |  c    |  3    |po
100     |  d    |  5    |no
101     |  a    |  1    |pm
101     |  b    |  5    |ceo
102     |  a    |  1    |rn
102     |  b    |  2    |han

在这里,同一个id检查2和5值,然后我们需要将检查值替换为2检查该id的值。

根据上表,我希望将加载/输出数据放入目标表中,如下所示

目标:emp1

id      | name  | check |deptname
100     |  a    |  1    |ceo
100     |  d    |  2    |hr
100     |  c    |  3    |po
101     |  a    |  1    |pm
101     |  b    |  5    |ceo
102     |  a    |  1    |rn
102     |  b    |  2    |han

我试过以下

select 
    a1.id,
    a1.name,
    isnull(a2.[check],a1.[check]) as [check]
from 
    emp as a1
left outer join 
    emp as a2 on a2.id = a1.id
              and a1.[check] in (2,5)
              and a2.[check] in (2,5)
              and a2.[check] <> a1.[check]
where 
    a2.id is null
    or (a1.[check] = 5
        and a2.[check] = 2)

该查询未返回正确的结果。

请告诉我如何编写查询以获取SQL Server中的预期输出

1 个答案:

答案 0 :(得分:0)

这是你如何做到的:

select
  e1.id,
  isnull(e2.name, e1.name) as name,
  e1.[check],
  e1.deptname
from emp e1
left outer join emp e2
  on e2.id = e1.id and e1.[check] = 2 and e2.[check] = 5
where
  not exists (select 1 from emp e3 where e3.id = e1.id and 
      e1.[check] = 5 and e3.[check] = 2)

SQL Fiddle

中的示例