SQL Server:更新同一个表中的值

[英]SQL Server : update a value within the same table


I want to use an update command for the table below. What I want to do is to update the answer column based on the reference column: 2nd and 3rd answers should be A because their reference is 1 and answer of the 1st row is A, similarly 5 and 6 should be X.

我想对下表使用更新命令。我想要做的是根据参考栏更新答案栏:第二和第三个答案应该是A,因为他们的参考是1,第一行答案是A,同样5和6应该是X.

Sample data:

样本数据:

id    answer  ref
-------------------
1       A      1
2       B      1
3       C      1
4       x      4
5       y      4
6       z      4

3 个解决方案

#1


2  

update a
set a.answer = b.answer
from tablename a, tablename b
where a.ref = b.id

edit: adding this also may be better;

编辑:添加这个也可能更好;

and a.ref <> a.id

#2


1  

update table1 t1 set answer = t2.answer from table1 t2 where t1.ref = t2.id;

update table1 t1 set answer = t2.answer from table1 t2 where t1.ref = t2.id;

#3


0  

You can use the case statement

您可以使用case语句

UPDATE sample_data
SET answer = ref
WHERE CASE 
      WHEN ref = 1
      THEN answer = 'A' 
      ELSE
      WHEN REF = 4
      THEN ANSWER = 'x'
END as available

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/02/24/8b15a91f4f86dd0f53be079af57748cf.html



 
  © 2014-2022 ITdaan.com 联系我们: