如何使用多个条件更新多个列

时间:2015-02-23 14:53:36

标签: sql-server 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 
          table1.year=d.year

如果表格匹配所有三列(州,月,年),则应仅更新权重列,如果匹配(州,年),则应仅更新州权重列如果匹配(年份),则应仅更新整体权重列

注意:我无法单独为每个条件写一个更新查询,因为它有一个巨大的select

表1

Year Month State Weight StateWeight Overweight
2014  1     AA    0.00    0.00        0.00
2014  3     AA    0.00    0.00        0.00
2014  1     AB    0.00    0.00        0.00
2014  2     AB    0.00    0.00        0.00
2014  3     AC    0.00    0.00        0.00
2014  1     DD    0.00    0.00        0.00

表2

Year Month State Weight StateWeight Overweight
2014  1     AA    2.20    5.00        2.22
2014  2     AA    1.70    5.00        2.22
2014  3     AA    8.30    5.00        2.22
2014  1     AB    5.80    2.11        2.22
2014  2     AB    7.40    2.11        2.22
2014  3     AB    9.10    2.11        2.22
2014  1     AC    3.42    5.14        2.22
2014  1     DD    8.88    9.00        2.22

我的结果应该是(我的更新表1应该是)

Year Month State Weight StateWeight Overweight
2014  1     AA    2.20    5.00        2.22
2014  3     AA    8.30    5.00        2.22
2014  1     AB    5.80    2.11        2.22
2014  2     AB    7.40    2.11        2.22
2014  3     AC    0.00    0.00        2.22
2014  1     DD    0.00    9.00        2.22

但是你给出的查询只更新了超重列而不是其他2列(权重和国家权重)

1 个答案:

答案 0 :(得分:1)

您可以通过更改where子句中的条件并将case语句添加到更新中来实现此目的。

以下是一个例子:

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;
相关问题