我需要更新具有多个条件的表中的多个列。
例如,这是我的查询
update Table1
set weight= d.weight,
stateweight=d.stateweight,
overallweight=d.overallweight
from
(select * from table2)d
where table1.state=d.state and
table1.month=d.month and
table1.year=d.year
如果表格匹配所有三列(州,月,年),它应仅更新权重列,如果匹配(州,年),它应仅更新州权重列,如果匹配(年),则应更新只有整体重量列
注意:我不能单独为每个条件写一个更新查询,因为它有一个巨大的表帮助我们
答案 0 :(得分:0)
好的,这是另一个,也许是你正在寻找的:
update Table1
set weight = case when table1.state = d.state and
table1.month = d.month and
table1.year = d.year
then d.weight
else weight end,
stateweight = case when table1.state = d.state and
table1.month <> d.month and
table1.year = d.year
then d.stateweight
else stateweight end,
overallweight = case when table1.state <> d.state and
table1.month <> d.month and
table1.year = d.year
then d.overallweight
else overallweight end
from
(select * from table2)d
where
table1.year=d.year
请注意,列会更新为自己的值,即相同的值但仍在事务中。
整体重量的情况可能需要其他条件,但我不确定您的需求。
旧答案:
这可能会有效,具体取决于您使用的dbms:
update Table1
set (weight,
stateweight,
overallweight) =
(select * from table2 d
where table1.state = d.state and
table1."month" = d."month" and
table1."year" = d."year")
年份和月份列在此处分隔,因为它们是保留字。
使用Core SQL-2003之外的以下功能: T641,&#34;多列分配&#34;
答案 1 :(得分:0)
with
cte as ( select t1.Year,
t1.Month,
t1.State,
Weight = MAX(case
when t1.State = t2.State and t1.Month = t2.Month
then t2.Weight
else t1.Weight
end),
StateWeight = MAX(case
when t1.State = t2.State and t1.Month = t2.Month
then t2.StateWeight
else t1.StateWeight
end),
Overweight = MAX(t2.Overweight)
from Table1 as t1
inner join Table2 as t2 on t1.Year = t2.Year
group by t1.Year, t1.Month, t1.State)
update t1
set Weight = tv.Weight,
StateWeight = tv.StateWeight,
Overweight = tv.Overweight
from Table1 as t1
inner join cte as tv on t1.Year = tv.Year
and t1.Month = tv.Month
and t1.State = tv.State;
它有效