简体   繁体   English

如何根据条件更新SQL SERVER DB中的表列

[英]How to Update table column in SQL SERVER DB based on condition

I have a table with the following information: 我有一张包含以下信息的表:

ID         Value_N1        Date_N1     Value_N4      Date_N4
1           NULL          2017-05-31    0.236        2017-02-28
2           NULL          2017-05-31    0.589        2017-02-28
3           NULL          2017-08-30    0.898        2017-08-30
4           NULL          2017-11-30    0.789        2017-11-30

I want to update the Value_N1 column with values from Value_N4 where Date_N1 is equal to Date_N4 我想用Value_N4中的值更新Value_N1列,其中Date_N1等于Date_N4

I have tried to use the following query but am going nowhere with it: 我尝试使用以下查询,但是却无济于事:

Update TableName
set Value_N1 = (select Value_N4 from TbleName where Date_N1 = Date_N4)

Of-cause this query doesn't work because it returns more than one value. 由于该查询返回的值不止一个,因此该查询不起作用。 How can this be achieved? 如何做到这一点?

You can also use a CASE expression. 您也可以使用CASE表达式。

Query 询问

update TableName
set Value_N1 = (
    case when Date_N1 = Date_N4
    then Value_N4
    else Value_N1 end
);

更新TableName设置Value_N1 = Value_N4,其中Date_N1 = Date_N4

Your logic for setting the new value to Value_N1 is on the right track, but the restrictions for which records to update should appear in a WHERE clause. 将新值设置为Value_N1逻辑是正确的,但是要更新记录的限制应出现在WHERE子句中。

UPDATE TableName
SET Value_N1 = Value_N4
WHERE Date_N1 = Date_N4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM