Sql 如何使用多种条件更新表
我需要用多个条件更新表中的多个列 例如,这是我的查询Sql 如何使用多种条件更新表,sql,database,Sql,Database,我需要用多个条件更新表中的多个列 例如,这是我的查询 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 ta
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
如果表匹配所有三列(州、月、年),则应仅更新权重列;如果表匹配(州、年),则应仅更新stateweight列;如果表匹配(年),则应仅更新overallweight列
注意:我不能单独为每个条件编写更新查询,因为它是一个巨大的表,请帮助我们好的,这里是另一个,可能是您需要的:
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
年和月列在这里是分隔的,因为它们是保留字
使用核心SQL-2003之外的以下功能:
T641,“多列分配”
它可以工作哪个数据库管理系统?(发布的查询不是ANSI SQL。)嗨,tks for replay,上面的查询只满足一个条件,那么其他两个条件呢(如果它匹配(state,year),它应该只更新stateweight列,如果它匹配(year),它应该只更新overallweight列)对不起,显然我读得不够仔细。。。稍后再看。
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")
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;