使用SQL Server更新变量列

时间:2017-04-20 18:16:40

标签: mysql sql

我有两张桌子。一种格式如下:

Id | FieldName | Value
0  | field1    | 0
1  | field2    | 0
2  | field3    | 0

第二种格式如下:

Id | field1 | field2 | field3
0  |   1    |   1    |   1
1  |   1    |   1    |   1
2  |   1    |   1    |   1

我需要更新第二个表,以便将1的值更改为0,其中fieldname列值与第二个表中的列值匹配。所以决赛桌应该是这样的:

Id | field1 | field2 | field3
0  |   0    |   1    |   1
1  |   1    |   0    |   1
2  |   1    |   1    |   0

1 个答案:

答案 0 :(得分:0)

试试这个: -

Select a.id,
Case when (fieldName='field1' and field1=1) then value else field1 end as field1,
Case when (fieldName='field2' and field2=1) then value else field2 end as field2,
Case when (fieldName='field3' and field3=1) then value else field3 end as field3
from 
table2 a
inner join
table1 b 
on a.id=b.id

感谢: - )