Sql 使用条件将字段从一列复制到另一列
我有一个名为02_Month的表格,包含以下信息:Sql 使用条件将字段从一列复制到另一列,sql,sql-server,ms-access,Sql,Sql Server,Ms Access,我有一个名为02_Month的表格,包含以下信息: |------------------------------------------------------------------ | Soc | Society | USD_STD | USD_STD_R | |------------------------------------------------------------------| | AB02 | P
|------------------------------------------------------------------
| Soc | Society | USD_STD | USD_STD_R |
|------------------------------------------------------------------|
| AB02 | Plants | 3.8 | 1 |
| JK01 | Trees | 2.4 | 1 |
| WB09 | Bushes | 1.2 | 3 |
| COIN | Flowers | 4.6 | 2 |
| KK99 | Stones | 66.9 | 3 |
| TCTC | Ruby | 19.0 | 5 |
| WNOL | Steel | 71.1 | 7 |
|------------------------------------------------------------------
如果Soc列是COIN或TCTC,我想将USD_STD列中的内容复制到USD_STD_R列。我想在最后说:
|------------------------------------------------------------------
| Soc | Society | USD_STD | USD_STD_R |
|------------------------------------------------------------------|
| AB02 | Plants | 3.8 | 1 |
| JK01 | Trees | 2.4 | 1 |
| WB09 | Bushes | 1.2 | 3 |
| COIN | Flowers | 4.6 | 4.6 |
| KK99 | Stones | 66.9 | 3 |
| TCTC | Ruby | 19.0 | 19.0 |
| WNOL | Steel | 71.1 | 7 |
|------------------------------------------------------------------
我写道:
UPDATE 02_Month
SET [02_Month].USD_STD_R = USD_STD
WHERE (([02_Month].Soc="COIN") or ([02_Month].Soc="TCTC"));
它没有按预期工作。我想这是由于WHERE
条件造成的。如果我不写那一行,它会用USD\U STD\R复制整列USD\U STD
我写的代码在USD\u STD\u R的所有字段中打印
0
。它为什么不起作用,如何更正?USD\u STD而不是STD\u USD
也可以在运算符中使用
UPDATE 02_Month
SET [02_Month].USD_STD_R = USD_STD
FROM [02_Month]
WHERE ([02_Month].Soc IN ('COIN','TCTC'));
请尝试以下查询。字符串值始终在“”内
您可以使用
内部连接更新
,如下所示
UPDATE a
SET a.USD_STD_R = b.USD_STD --You can change another column here as per your need.
FROM [02_Month] a
INNER JOIN [02_Month] b ON a.soc = b.soc
AND a.society = b.society
AND a.USD_STD = b.USD_STD
AND a.USD_STD_R = b.USD_STD_R
WHERE a.Soc in ('COIN','TCTC');
如果不希望使用别名更新表
UPDATE [02_Month]
SET [02_Month].USD_STD_R = b.USD_STD --You can change another column here as per your need.
FROM [02_Month]
INNER JOIN [02_Month] b ON [02_Month].soc = b.soc
AND [02_Month].society = b.society
AND [02_Month].USD_STD = b.USD_STD
AND [02_Month].USD_STD_R = b.USD_STD_R
WHERE [02_Month].Soc in ('COIN','TCTC');
您的02\u月与列字段USD\u STD USD\u STD\R的关系,但在更新语句中,列字段名称为STD\u USD\R和STD\u USD 以下内容应足够:
update [02_month] t
set t.usd_std_r = t.usd_std
where t.soc="COIN" or t.soc="TCTC"
请注意:
- 由于表名以数字开头,因此必须用方括号括起来
- 使用
只是为了避免重复写入t
[02\u month]
- 您可以使用
或t.soc=“COIN”或t.soc=“TCTC”
这两种方法都应产生相同的结果t.soc in(“COIN”、“TCTC”)
- 双引号
通常由MS Access使用,但单引号“
也应有效”
update [02_month] t
set t.usd_std_r = t.usd_std
where t.soc="COIN" or t.soc="TCTC"